gpt4 book ai didi

python - 绘制数千条柱形图时是否可以加快柱形图绘制速度?

转载 作者:太空宇宙 更新时间:2023-11-03 20:12:21 24 4
gpt4 key购买 nike

原始问题:我需要绘制一对图表,每个图表有数千个水平条。我得到的唯一合理的输出格式是使用 Matplotlib 的 hbar。我准备了一个简化的代码,它生成一些随机图形并绘制我使用的相同图表(请参见下图后面的代码;您可能需要更改图形的大小,以便可以在屏幕上看到整个图片)。

在我的笔记本电脑(联想 Yoga 920;第 8 代英特尔酷睿 i7-8550U)上,绘制图表需要几乎一分钟的时间。我可以做些什么来使这些图表更快地绘制出来吗?

更新和解决方案:根据 @ImportanceOfBeingErnest 的建议,我使用 LineCollection 进行了一个快速实验。我将这项研究纳入了我自己的答案中 - 希望它能帮助一些程序员更快地理解 LineCollection 的工作原理。经过研究,我最终写出了代码。现在需要一秒多一点的时间来绘制与我的原始图表非常相似的图表!

我需要绘制的图表 enter image description here

原始代码

def chart_size_and_font (width, length, font):

import matplotlib.pyplot as plt

fig_size = plt.rcParams["figure.figsize"] #set chart size; as multiples charts will be ploted, the overall chart needs to be big
fig_size[0] = width
fig_size[1] = length
plt.rcParams["figure.figsize"] = fig_size
plt.rcParams.update({'font.size': font}) #set font size for all charts (title, axis etc)

import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
from datetime import datetime, timedelta

# generating some random figures
sim_days = [datetime.today() - timedelta(days=x) for x in range(2000)]
positive_1 = np.random.normal(100, 20, (2000,4))
negative_1 = np.random.normal(-100, 20, (2000,4))
positive_2 = np.random.normal(100, 20, (2000,4))
negative_2 = np.random.normal(-100, 20, (2000,4))

run_start = timer()
time_now = datetime.now().strftime('%H:%M:%S')
print("-----------------------------------------")
print("Run start time:", time_now)
print("-----------------------------------------")

#color map (repeating sequence in case plotting more contributor than the original four most positive/negative)
color_map_blue = ['mediumblue','royalblue','dodgerblue','skyblue', 'mediumblue','royalblue','dodgerblue','skyblue']
color_map_red = ['firebrick','red','salmon','mistyrose', 'firebrick','red','salmon','mistyrose']

chart_size_and_font (39, 30, 20) # set charts width, lenght and fonts

chart_f = plt.figure()
st = chart_f.suptitle("FIGURE TITLE", fontsize=25)
st.set_y(0.93) #move position of suptitle; zero puts it at bottom of chart

days = positive_1.shape[0] #same as "len" of array
count = positive_1.shape[1] #number of columns

chart_p = plt.subplot(1,2,1)
pos_left = np.zeros(days)
neg_left = np.zeros(days)
for n in range(count):
chart_p = plt.barh(y=sim_days, width=positive_1[:,n], left=pos_left, align='center', height=2, color = color_map_blue[n])
pos_left += positive_1[:,n]
chart_p = plt.barh(y=sim_days, width=negative_1[:,n], left=neg_left, align='center', height=2, color = color_map_red[n])
neg_left += negative_1[:,n]
plt.title("SUBPLOT 1 TITLE", fontsize=20)
ax = plt.gca() # get current axis ('x' and 'y') to be formated
ax.set_xticklabels(['{:,.0f}'.format(x) for x in ax.get_xticks().tolist()]) # format x-axis labels
plt.grid()

chart_p = plt.subplot(1,2,2)
pos_left = np.zeros(days)
neg_left = np.zeros(days)
for n in range(count):
chart_p = plt.barh(y=sim_days, width=positive_2[:,n], left=pos_left, align='center', height=2, color = color_map_blue[n])
pos_left += positive_2[:,n]
chart_p = plt.barh(y=sim_days, width=negative_2[:,n], left=neg_left, align='center', height=2, color = color_map_red[n])
neg_left += negative_2[:,n]
plt.title("SUBPLOT 2 TITLE", fontsize=20)
ax = plt.gca() # get current axis ('x' and 'y') to be formated
ax.set_xticklabels(['{:,.0f}'.format(x) for x in ax.get_xticks().tolist()]) # format x-axis labels
plt.grid()

plt.show()

run_end = timer()
time_now = datetime.now().strftime('%H:%M:%S')
print("\n-----------------------------------------")
print("Run end time: ", time_now)
print("Time to run:", timedelta(seconds=run_end-run_start))
print("-----------------------------------------")

最佳答案

根据 @ImportanceOfBeingErnest 的指导,我准备了一项关于如何使用 LineCollection 绘制一大组线条的研究。研究结束后,最终的解决方案是:用一段代码在一秒钟内绘制出与我原来的图表非常相似的图表!

研究

下面是绘制一系列线条的代码。下图显示了 20 条线:易于跟踪颜色和线宽的变化。绘图需要零时间。第二个图显示了 2000 行:绘制需要 1.3 秒。

20 lines plot

2,000 lines plot

学习代码

import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

import numpy as np
from numpy import array
from timeit import default_timer as timer
from datetime import datetime, timedelta

line_number = 2000

day = array(range(0,line_number))
change = np.random.rand(line_number)
all_zeros = np.zeros(line_number)

run_start = timer()
time_now = datetime.now().strftime('%H:%M:%S')
print("-----------------------------------------")
print("Run start time:", time_now)
print("-----------------------------------------")

color_map = ['red', 'blue','green','orange','pink']

# We need to set the plot limits.
ax = plt.axes()
ax.set_xlim(0, change.max()*3)
ax.set_ylim(0, day.max()*3)

segs = np.zeros((line_number, 4, 2), float) # the 1st argument refers to how many lines will be plotted; the 2nd argument to coordinates per lines (which will plot one fewer line-segments as you need two coordinates to form the first line-segment); the 3rd argument refers to the X/Y axes

segs[:,0,1] = day # Y-axis
segs[:,0,0] = all_zeros # X-axis / setting using the variable "all zeros" not necessary (as segs was already all zeros) - included for clarity

segs[:,1,1] = day*2 # this is the 2nd data-point, forming the first line segment
segs[:,1,0] = change

segs[:,2,1] = day*1.5 # this is the 3rd data-point, forming the second line segment
segs[:,2,0] = change*2

segs[:,3,1] = day*2.5 # this is the 4th data-point, forming the 3rd line segment
segs[:,3,0] = change*3

line_segments = LineCollection(segs, linewidths=(4, 3, 2, 1, 0.5), colors=color_map) # the color_map will be used by "complete segment"
ax.add_collection(line_segments)

ax.set_title('Plot test: ' + str(line_number) + ' lines with LineCollection')
plt.show()

run_end = timer()
time_now = datetime.now().strftime('%H:%M:%S')
print("\n-----------------------------------------")
print("Run end time: ", time_now)
print("Time to run:", timedelta(seconds=run_end-run_start))
print("-----------------------------------------")

最终代码

# LineCollection chart

def chart_size_and_font(width, length, font):

import matplotlib.pyplot as plt

fig_size = plt.rcParams["figure.figsize"] #set chart size; as multiples charts will be ploted, the overall chart needs to be big
fig_size[0] = width
fig_size[1] = length
plt.rcParams["figure.figsize"] = fig_size
plt.rcParams.update({'font.size': font}) #set font size for all charts (title, axis etc)


import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

import numpy as np
from numpy import array
from timeit import default_timer as timer
from datetime import datetime, timedelta

dates = 2000

# generating some random figures
sim_days = array(range(0,dates))
positive_1 = np.random.normal(100, 20, (dates,4))
negative_1 = np.random.normal(-100, 20, (dates,4))
positive_2 = np.random.normal(100, 20, (dates,4))
negative_2 = np.random.normal(-100, 20, (dates,4))

run_start = timer()
time_now = datetime.now().strftime('%H:%M:%S')
print("-----------------------------------------")
print("Run start time:", time_now)
print("-----------------------------------------")

days = positive_1.shape[0] # same as "len" of array
count = positive_1.shape[1] # number of columns

#color map (repeating sequence in case plotting more contributor than the original four most positive/negative)
color_map_blue = ['mediumblue','royalblue','dodgerblue','skyblue', 'mediumblue','royalblue','dodgerblue','skyblue']
color_map_red = ['firebrick','red','salmon','mistyrose', 'firebrick','red','salmon','mistyrose']

chart_size_and_font (40, 40, 20) # set charts width, lenght and fonts
chart_f = plt.figure()
st = chart_f.suptitle("FIGURE TITLE", fontsize=25)
st.set_y(0.93) #move position of suptitle; zero puts it at bottom of chart

chart_p = plt.subplot(1,2,1)

pos_sum = np.sum(positive_1, axis=1) # add array rows
neg_sum = np.sum(negative_1, axis=1)
chart_p.set_xlim(neg_sum.min(), pos_sum.max()) #set plot axes limits
chart_p.set_ylim(0, sim_days.max())

coord_1 = np.zeros(dates)
coord_2 = np.zeros(dates)
for n in range(count): # plot positive values on first chart
coord_2 += positive_1[:,n]
segs = np.zeros((dates, 2, 2), float)
segs[:,0,0] = coord_1 # X-axis coordinates - start of line
segs[:,0,1] = sim_days # Y-axis coordinates - start of line
segs[:,1,0] = coord_2 # X-axis corrdinates - end of line
segs[:,1,1] = sim_days # Y-axis coordinates - end of line
line_segments = LineCollection(segs, linewidths=2, colors=color_map_blue[n])
chart_p.add_collection(line_segments)
coord_1 += positive_1[:,n]

coord_1 = np.zeros(dates)
coord_2 = np.zeros(dates)
for n in range(count): # plot negative values on first chart
coord_2 += negative_1[:,n]
segs = np.zeros((dates, 2, 2), float)
segs[:,0,0] = coord_1
segs[:,0,1] = sim_days
segs[:,1,0] = coord_2
segs[:,1,1] = sim_days
line_segments = LineCollection(segs, linewidths=2, colors=color_map_red[n])
chart_p.add_collection(line_segments)
coord_1 += negative_1[:,n]

chart_p.set_title('Plot test 1: ' + str(dates) + ' lines with LineCollection')
plt.grid()


chart_p = plt.subplot(1,2,2)

pos_sum = np.sum(positive_2, axis=1) # add array rows
neg_sum = np.sum(negative_2, axis=1)
chart_p.set_xlim(neg_sum.min(), pos_sum.max()) #set plot axes limits
chart_p.set_ylim(0, sim_days.max())

coord_1 = np.zeros(dates)
coord_2 = np.zeros(dates)
for n in range(count): # plot positive values on first chart
coord_2 += positive_2[:,n]
segs = np.zeros((dates, 2, 2), float)
segs[:,0,0] = coord_1 # X-axis coordinates - start of line
segs[:,0,1] = sim_days # Y-axis coordinates - start of line
segs[:,1,0] = coord_2 # X-axis corrdinates - end of line
segs[:,1,1] = sim_days # Y-axis coordinates - end of line
line_segments = LineCollection(segs, linewidths=2, colors=color_map_blue[n])
chart_p.add_collection(line_segments)
coord_1 += positive_2[:,n]

coord_1 = np.zeros(dates)
coord_2 = np.zeros(dates)
for n in range(count): # plot negative values on first chart
coord_2 += negative_2[:,n]
segs = np.zeros((dates, 2, 2), float)
segs[:,0,0] = coord_1
segs[:,0,1] = sim_days
segs[:,1,0] = coord_2
segs[:,1,1] = sim_days
line_segments = LineCollection(segs, linewidths=2, colors=color_map_red[n])
chart_p.add_collection(line_segments)
coord_1 += negative_2[:,n]

chart_p.set_title('Plot test 2: ' + str(dates) + ' lines with LineCollection')
plt.grid()

plt.show()


run_end = timer()
time_now = datetime.now().strftime('%H:%M:%S')
print("\n-----------------------------------------")
print("Run end time: ", time_now)
print("Time to run:", timedelta(seconds=run_end-run_start))
print("-----------------------------------------")

最终图表

我仍然需要设置 Y 轴标签的格式,因为我无法使用“日期”作为 Y 轴值。然而,结果与我的原始图表非常相似(但绘制速度快了 50 倍):

Final chart

关于python - 绘制数千条柱形图时是否可以加快柱形图绘制速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58648287/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com