pandas 熊猫:用标签绘制时间序列的多列(熊猫文档中的示例)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26845727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pandas: plot multiple columns of a timeseries with labels (example from pandas documentation)
提问by bjelli
I'm trying to recreate the example of plot multiple columns of a timeseries with labels as shown in the pandas documentation here: http://pandas.pydata.org/pandas-docs/dev/visualization.html#visualization-basic(second graph)
我正在尝试重新创建使用标签绘制时间序列的多列的示例,如Pandas文档中所示:http: //pandas.pydata.org/pandas-docs/dev/visualization.html#visualization-basic(第二图形)


Here's my code:
这是我的代码:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
ts = pd.DataFrame(np.random.randn(1000, 4), index=pd.date_range('1/1/2000', periods=1000), columns=list('ABCD'))
ts = ts.cumsum()
fig = plt.figure()
print ts.head()
ts.plot()
fig.savefig("x.png")
the text output seems ok:
文本输出似乎没问题:
A B C D
2000-01-01 1.547838 -0.571000 -1.780852 0.559283
2000-01-02 1.165659 -1.859979 -0.490980 0.796502
2000-01-03 0.786416 -2.543543 -0.903669 1.117328
2000-01-04 1.640174 -3.756809 -1.862188 0.466236
2000-01-05 2.119575 -4.590741 -1.055563 1.004607
but x.png is always empty.
但 x.png 总是空的。
If I plot just one column:
如果我只绘制一列:
ts['A'].plot()
I do get a result.
我确实得到了结果。
Is there a way to debug this, to find out what's going wrong here?
有没有办法调试这个,找出这里出了什么问题?
采纳答案by joris
The reason you don't get a result is because you are not saving the 'correct' figure: you are making a figure with plt.figure(), but pandas does not plot on the current figure, and will create a new one.
If you do:
您没有得到结果的原因是因为您没有保存“正确”的图形:您正在使用 制作图形plt.figure(),但Pandas不会在当前图形上绘图,而是会创建一个新图形。
如果你这样做:
ts.plot()
fig = plt.gcf() # get current figure
fig.savefig("x.png")
I get the correct output. When plotting a Series, it doesuse the current axis if no axis is passed.
But it seems that the pandas docs are not fully correct on that account (as they use the plt.figure()), I reported an issue for that: https://github.com/pydata/pandas/issues/8776
我得到正确的输出。绘制系列时,如果没有传递轴,它会使用当前轴。
但似乎该帐户上的 Pandas 文档并不完全正确(因为他们使用plt.figure()),我为此报告了一个问题:https: //github.com/pydata/pandas/issues/8776
Another option is to provide an axes object using the axargument:
另一种选择是使用ax参数提供一个轴对象:
fig = plt.figure()
ts.plot(ax=plt.gca()) # 'get current axis'
fig.savefig("x.png")
or slightly cleaner (IMO):
或稍微清洁一点(IMO):
fig, ax = plt.subplots()
ts.plot(ax=ax)
fig.savefig("x.png")

