- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
原始问题:我需要绘制一对图表,每个图表有数千个水平条。我得到的唯一合理的输出格式是使用 Matplotlib 的 hbar。我准备了一个简化的代码,它生成一些随机图形并绘制我使用的相同图表(请参见下图后面的代码;您可能需要更改图形的大小,以便可以在屏幕上看到整个图片)。
在我的笔记本电脑(联想 Yoga 920;第 8 代英特尔酷睿 i7-8550U)上,绘制图表需要几乎一分钟的时间。我可以做些什么来使这些图表更快地绘制出来吗?
更新和解决方案:根据 @ImportanceOfBeingErnest 的建议,我使用 LineCollection 进行了一个快速实验。我将这项研究纳入了我自己的答案中 - 希望它能帮助一些程序员更快地理解 LineCollection 的工作原理。经过研究,我最终写出了代码。现在需要一秒多一点的时间来绘制与我的原始图表非常相似的图表!
原始代码
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 秒。
学习代码
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 倍):
关于python - 绘制数千条柱形图时是否可以加快柱形图绘制速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58648287/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!