Python matplotlib program hangs after every interval after using for loop

Below is my python matplotlib code. It was working fine until I used the for loop in it to reduce the repeated code lines. Now, after every 1 second, the bar chart window hangs for 1 second. When I try to mouse hover on the bar chart it hangs for every 1 second. Also, when I try to drag the entire window on screen then also, it hangs for every 1 second.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import os
from importlib import reload
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation
import cred
def run_script():
"""
This function runs the script.
"""
# Set the background color of the entire window
plt.rcParams["figure.facecolor"] = "#131722"
plt.style.use("fivethirtyeight")
fig, axs = plt.subplots(3, 1, figsize=(10, 8), sharex=True)
# Set background color
fig.patch.set_facecolor("#131722")
for ax in axs:
ax.set_facecolor("#131722")
def animatechart(i):
reload(cred)
fold = os.path.join(os.getcwd(), "data")
bnifty_csv = os.path.join(fold, f"{cred.symbol0.split(":")[1]}.csv")
pe_csv = os.path.join(fold, f"{cred.symbol1.split(":")[1]}.csv")
ce_csv = os.path.join(fold, f"{cred.symbol2.split(":")[1]}.csv")
chart_path = os.path.join(os.getcwd(), "images")
chart = os.path.join(chart_path, "chart2.png")
while True:
try:
bankniftydata = pd.read_csv(bnifty_csv, skip_blank_lines=True)
pedata = pd.read_csv(pe_csv, skip_blank_lines=True)
cedata = pd.read_csv(ce_csv, skip_blank_lines=True)
except Exception as e:
e = "Exception Occured!"
print(e)
continue
break
option_data = pd.merge(pedata, cedata, on="Time", how="inner")
data = pd.merge(bankniftydata, option_data, on="Time", how="inner")
symbols = [cred.symbol0, cred.symbol1, cred.symbol2]
for symbol, ax in zip(symbols, axs):
ax.clear()
ax.bar(
data["Time"],
data[f"{symbol.split(":")[1]}Volume"],
color="#9598a1",
)
ax.axis("off")
ax.autoscale(tight=True)
ax.set_title(
f"{symbol.split(":")[1]} {cred.resolution} {cred.from_date()} {cred.to_date()}",
loc="left",
color="#9598a1",
fontsize=12,
)
plt.tight_layout()
plt.savefig(chart, facecolor="#131722", bbox_inches="tight")
ani = FuncAnimation(
plt.gcf(),
animatechart,
interval=1000,
cache_frame_data=False,
)
plt.show()
run_script()
</code>
<code>import os from importlib import reload import matplotlib.pyplot as plt import pandas as pd from matplotlib.animation import FuncAnimation import cred def run_script(): """ This function runs the script. """ # Set the background color of the entire window plt.rcParams["figure.facecolor"] = "#131722" plt.style.use("fivethirtyeight") fig, axs = plt.subplots(3, 1, figsize=(10, 8), sharex=True) # Set background color fig.patch.set_facecolor("#131722") for ax in axs: ax.set_facecolor("#131722") def animatechart(i): reload(cred) fold = os.path.join(os.getcwd(), "data") bnifty_csv = os.path.join(fold, f"{cred.symbol0.split(":")[1]}.csv") pe_csv = os.path.join(fold, f"{cred.symbol1.split(":")[1]}.csv") ce_csv = os.path.join(fold, f"{cred.symbol2.split(":")[1]}.csv") chart_path = os.path.join(os.getcwd(), "images") chart = os.path.join(chart_path, "chart2.png") while True: try: bankniftydata = pd.read_csv(bnifty_csv, skip_blank_lines=True) pedata = pd.read_csv(pe_csv, skip_blank_lines=True) cedata = pd.read_csv(ce_csv, skip_blank_lines=True) except Exception as e: e = "Exception Occured!" print(e) continue break option_data = pd.merge(pedata, cedata, on="Time", how="inner") data = pd.merge(bankniftydata, option_data, on="Time", how="inner") symbols = [cred.symbol0, cred.symbol1, cred.symbol2] for symbol, ax in zip(symbols, axs): ax.clear() ax.bar( data["Time"], data[f"{symbol.split(":")[1]}Volume"], color="#9598a1", ) ax.axis("off") ax.autoscale(tight=True) ax.set_title( f"{symbol.split(":")[1]} {cred.resolution} {cred.from_date()} {cred.to_date()}", loc="left", color="#9598a1", fontsize=12, ) plt.tight_layout() plt.savefig(chart, facecolor="#131722", bbox_inches="tight") ani = FuncAnimation( plt.gcf(), animatechart, interval=1000, cache_frame_data=False, ) plt.show() run_script() </code>
import os
from importlib import reload

import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.animation import FuncAnimation

import cred


def run_script():
    """
    This function runs the script.
    """
    # Set the background color of the entire window
    plt.rcParams["figure.facecolor"] = "#131722"
    plt.style.use("fivethirtyeight")
    fig, axs = plt.subplots(3, 1, figsize=(10, 8), sharex=True)

    # Set background color
    fig.patch.set_facecolor("#131722")
    for ax in axs:
        ax.set_facecolor("#131722")

    def animatechart(i):
        reload(cred)
        fold = os.path.join(os.getcwd(), "data")
        bnifty_csv = os.path.join(fold, f"{cred.symbol0.split(":")[1]}.csv")
        pe_csv = os.path.join(fold, f"{cred.symbol1.split(":")[1]}.csv")
        ce_csv = os.path.join(fold, f"{cred.symbol2.split(":")[1]}.csv")

        chart_path = os.path.join(os.getcwd(), "images")
        chart = os.path.join(chart_path, "chart2.png")
        while True:
            try:
                bankniftydata = pd.read_csv(bnifty_csv, skip_blank_lines=True)
                pedata = pd.read_csv(pe_csv, skip_blank_lines=True)
                cedata = pd.read_csv(ce_csv, skip_blank_lines=True)
            except Exception as e:
                e = "Exception Occured!"
                print(e)
                continue
            break
        option_data = pd.merge(pedata, cedata, on="Time", how="inner")
        data = pd.merge(bankniftydata, option_data, on="Time", how="inner")

        symbols = [cred.symbol0, cred.symbol1, cred.symbol2]
        for symbol, ax in zip(symbols, axs):
            ax.clear()
            ax.bar(
                data["Time"],
                data[f"{symbol.split(":")[1]}Volume"],
                color="#9598a1",
            )
            ax.axis("off")
            ax.autoscale(tight=True)
            ax.set_title(
                f"{symbol.split(":")[1]}   {cred.resolution}   {cred.from_date()}   {cred.to_date()}",
                loc="left",
                color="#9598a1",
                fontsize=12,
            )

        plt.tight_layout()
        plt.savefig(chart, facecolor="#131722", bbox_inches="tight")

    ani = FuncAnimation(
        plt.gcf(),
        animatechart,
        interval=1000,
        cache_frame_data=False,
    )
    plt.show()


run_script()

For now, I didn’t find any solution yet to try.
If I don’t use for loop then the program does not hang after every interval. But I want to use for loop to optimize the code which leads to hanging.

Additional Information:
CPU: Intel Core i5 14th Gen
Memory: 32 GB

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật