Python 在同一图中绘制不同的 DataFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13872533/
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
Plot different DataFrames in the same figure
提问by wuwucat
I have a temperature file with many years temperature records, in a format as below:
我有一个带有多年温度记录的温度文件,格式如下:
2012-04-12,16:13:09,20.6
2012-04-12,17:13:09,20.9
2012-04-12,18:13:09,20.6
2007-05-12,19:13:09,5.4
2007-05-12,20:13:09,20.6
2007-05-12,20:13:09,20.6
2005-08-11,11:13:09,20.6
2005-08-11,11:13:09,17.5
2005-08-13,07:13:09,20.6
2006-04-13,01:13:09,20.6
Every year has different numbers, time of the records, so the pandas datetimeindices are all different.
每年都有不同的数字,记录的时间,所以熊猫的日期时间索引都是不同的。
I want to plot the different year's data in the same figure for comparing . The X-axis is Jan to Dec, the Y-axis is temperature. How should I go about doing this?
我想在同一图中绘制不同年份的数据以进行比较。X 轴是 Jan 到 Dec,Y 轴是温度。我该怎么做呢?
采纳答案by Andy Hayden
Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupbyand unstacking:
尽管 Chang 的回答解释了如何在同一个图形上多次绘制,但在这种情况下,在这种情况下使用 agroupby和unstacking可能会更好:
(Assuming you have this in dataframe, with datetime index already)
(假设你在数据框中有这个,日期时间索引已经)
In [1]: df
Out[1]:
value
datetime
2010-01-01 1
2010-02-01 1
2009-01-01 1
# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)
In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
value
Year 2009 2010
Month
1 1 1
2 NaN 1
Now it's easy to plot (each year as a separate line):
现在很容易绘制(每年作为单独的一行):
df.groupby(['Month','Year']).mean().unstack().plot()
回答by Chang She
Try:
尝试:
ax = df1.plot()
df2.plot(ax=ax)
回答by Hamish Robertson
If you a running Jupyter/Ipython notebook and having problems using;
如果您正在运行 Jupyter/Ipython 笔记本并且在使用时遇到问题;
ax = df1.plot()
ax = df1.plot()
df2.plot(ax=ax)
df2.plot(ax=ax)
Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.
在同一个单元格内运行命令!!由于某种原因,当它们被分成连续的单元格时,它不会工作。至少对我来说。
回答by adivis12
To do this for multiple dataframes, you can do a for loop over them:
要对多个数据帧执行此操作,您可以对它们执行 for 循环:
fig = plt.figure(num=None, figsize=(10, 8))
ax = dict_of_dfs['FOO'].column.plot()
for BAR in dict_of_dfs.keys():
if BAR == 'FOO':
pass
else:
dict_of_dfs[BAR].column.plot(ax=ax)
回答by konse
Just to enhance @adivis12 answer, you don't need to do the ifstatement. Put it like this:
只是为了增强@adivis12 的回答,你不需要做这个if陈述。把它像这样:
fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
dict_of_dfs[BAR].plot(ax=ax)

