gpt4 book ai didi

python-2.7 - 使用循环绘制 n 个图表 Python

转载 作者:行者123 更新时间:2023-12-03 09:06:28 25 4
gpt4 key购买 nike

我有一组使用 Pandas 数据框加载到 python 中的数据。我想要做的是创建一个循环,该循环将为它们自己框架中的所有元素打印一个图,而不是全部打印在一个图上。我的数据位于以这种方式构建的 excel 文件中:

Index | DATE  | AMB CO 1 | AMB CO 2 |...|AMB CO_n | TOTAL
1 | 1/1/12| 14 | 33 |...| 236 | 1600
. | ... | ... | ... |...| ... | ...
. | ... | ... | ... |...| ... | ...
. | ... | ... | ... |...| ... | ...
n

到目前为止,这是我的代码:
import pandas as pd
import matplotlib.pyplot as plt
ambdf = pd.read_excel('Ambulance.xlsx',
sheetname='Sheet2', index_col=0, na_values=['NA'])
print type(ambdf)
print ambdf
print ambdf['EAS']

amb_plot = plt.plot(ambdf['EAS'], linewidth=2)
plt.title('EAS Ambulance Numbers')
plt.xlabel('Month')
plt.ylabel('Count of Deliveries')
print amb_plot

for i in ambdf:
print plt.plot(ambdf[i], linewidth = 2)

我正在考虑做这样的事情:
for i in ambdf:
ambdf_plot = plt.plot(ambdf, linewidth = 2)

以上并不是我想要的,它源于我对 Pandas、MatplotLib 等的不熟悉,查看了一些文档,但在我看来似乎甚至不需要 matplotlib(问题 2)

所以 A)如何为我的 df 中的每一列生成数据图
和 B) 我需要使用 matplotlib 还是应该只使用 Pandas 来完成这一切?

谢谢,

最佳答案

好的,所以创建多个图的最简单方法是:

import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
for i in range(len(x)):
plt.figure()
plt.plot(x[i],y[i])
# Show/save figure as desired.
plt.show()
# Can show all four figures at once by calling plt.show() here, outside the loop.
#plt.show()

请注意,您需要创建一个 figure每次或 pyplot将在创建的第一个中绘图。

如果您想创建多个数据系列,您需要做的就是:
import matplotlib.pyplot as plt
plt.figure()
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
plt.plot(x[0],y[0],'r',x[1],y[1],'g',x[2],y[2],'b',x[3],y[3],'k')

你可以通过像 ['r','g','b','k'] 这样的颜色列表来自动化它。然后,如果您愿意,只需调用此列表中的两个条目以及要在循环中绘制的相应数据。如果您只想以编程方式将数据系列添加到一个图中,这样的事情就可以做到(每次都不会创建新图形,因此所有内容都绘制在同一个图形中):
import matplotlib.pyplot as plt
x=[[1,2,3,4],[1,2,3,4],[1,2,3,4],[1,2,3,4]]
y=[[1,2,3,4],[2,3,4,5],[3,4,5,6],[7,8,9,10]]
colours=['r','g','b','k']
plt.figure() # In this example, all the plots will be in one figure.
for i in range(len(x)):
plt.plot(x[i],y[i],colours[i])
plt.show()

希望这可以帮助。如果有什么 matplotlib 有一个很好的 documentation page大量 examples .

2019 年 12 月 17 日:添加 plt.show()plt.figure()呼吁澄清这部分故事。

关于python-2.7 - 使用循环绘制 n 个图表 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19189488/

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