如何将数据框中的不同数据组绘制成单个图形
- 2025-03-10 08:50:00
- admin 原创
- 38
问题描述:
我有一个温度文件,其中包含多年的温度记录,格式如下:
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
每年的记录次数都不同,因此熊猫 datetimeindices
都是不同的。
我想在同一张图中绘制不同年份的数据以便进行比较:
X 轴
datetimeindices
为 1 月至 12 月Y 轴是温度
我该如何做呢?
解决方案 1:
尝试:
ax = df1.plot()
df2.plot(ax=ax)
解决方案 2:
如果您正在运行 Jupyter/Ipython 笔记本并且在使用时遇到问题;
ax = df1.plot()
df2.plot(ax=ax)
在同一个单元格内运行命令!!出于某种原因,当它们被分成连续的单元格时,它不会起作用。至少对我来说是这样。
解决方案 3:
Chang 的回答展示了如何在同一个上绘制不同的 DataFrame
axes
。在这种情况下,所有数据都在同一个数据框中,因此最好使用
groupby
和unstack
。或者,
pandas.DataFrame.pivot_table
也可以使用。dfp = df.pivot_table(index='Month', columns='Year', values='value', aggfunc='mean')
使用 时
pandas.read_csv
,names=
如果文件中没有列标题,则会创建列标题。'date'
必须将 列解析为datetime64[ns] Dtype
,以便.dt
提取器可用于提取month
和year
。
import pandas as pd
# given the data in a file as shown in the op
df = pd.read_csv('temp.csv', names=['date', 'time', 'value'], parse_dates=['date'])
# create additional month and year columns for convenience
df['Year'] = df.date.dt.year
df['Month'] = df.date.dt.month
# groupby the month a year and aggreate mean on the value column
dfg = df.groupby(['Month', 'Year'])['value'].mean().unstack()
# display(dfg)
Year 2005 2006 2007 2012
Month
4 NaN 20.6 NaN 20.7
5 NaN NaN 15.533333 NaN
8 19.566667 NaN NaN NaN
现在很容易将每年绘制为一条单独的线。OP 每年只有一个观察值,因此只显示一个标记。
ax = dfg.plot(figsize=(9, 7), marker='.', xticks=dfg.index)
解决方案 4:
要对多个数据框执行此操作,可以对它们执行 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)
这也可以在没有if
条件的情况下实现:
fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
dict_of_dfs[BAR].plot(ax=ax)
解决方案 5:
您可以使用hue
中的参数seaborn
。例如:
import seaborn as sns
df = sns.load_dataset('flights')
year month passengers
0 1949 Jan 112
1 1949 Feb 118
2 1949 Mar 132
3 1949 Apr 129
4 1949 May 121
.. ... ... ...
139 1960 Aug 606
140 1960 Sep 508
141 1960 Oct 461
142 1960 Nov 390
143 1960 Dec 432
sns.lineplot(x='month', y='passengers', hue='year', data=df)
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD