绘制成千上万的条时,是否可以加快条状图的绘制?

时间:2019-10-31 17:12:27

标签: python matplotlib

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

在我的笔记本电脑(联想Yoga 920;第8代Intel Core 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("-----------------------------------------")

1 个答案:

答案 0 :(得分:0)

我使用@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