我使用此代码对平均值进行分组。按年份和大陆划分的预期生命周期:
avg_lifeExp_by_cont_yr = df.groupby(['year','continent'])['lifeExp'].mean()
结果如下所示:
我想创建一个折线图,在 x 轴上有年份,avg。 y 轴上的预期生命周期,以及用作图例的大陆(因此每个大陆一条线)。
最佳答案
您可以使用 df.unstack('continent')
把大洲作为列,那么这个dataframe就变成了一个二维表,第一列是X,其他列是Y。你可以直接调用plot
通过原始 matplotlib 操作自己运行或控制绘图。
感谢您提供数据,以下是您请求的完整代码示例:
# imports
import pandas as pd
import matplotlib.pyplot as plt
# prepare dataframe
df = pd.read_csv('gapminder.tsv', sep='\t')
df = df.groupby(['year','continent']).lifeExp.mean()
# unstack the `continent` index, to place it as columns
df = df.unstack(level='continent')
# The name of columns would become the name of legend
# when using dataframe plot
df.columns.name = 'Life Expectation'
# Now, we have a 2d talbe, 1st column become to X
# and other columns become to Y
# In [14]: df.head()
# Out[14]:
# Life Expectation Africa Americas Asia Europe Oceania
# year
# 1952 39.135500 53.27984 46.314394 64.408500 69.255
# 1957 41.266346 55.96028 49.318544 66.703067 70.295
# 1962 43.319442 58.39876 51.563223 68.539233 71.085
# 1967 45.334538 60.41092 54.663640 69.737600 71.310
# 1972 47.450942 62.39492 57.319269 70.775033 71.910
# matplotlib operations
# Here we use dataframe plot function
# You could also use raw matplotlib plot one column each to do fine control
# Please polish the figure with more configurations
fig, ax = plt.subplots(figsize=(6, 4.5))
df.plot()
数据处理有几个技巧,请查看代码中的注释。粗略的情节看起来像
请用更多的 matplotlib 操作润色你的图。例如:
这里有一些调整
# set axis labels
ax.set_xlabel('Year')
ax.set_ylabel('Life Expection')
# set markers
markers = ['o', 's', 'd', '^', 'v']
for i, line in enumerate(ax.get_lines()):
line.set_marker(markers[i])
# update legend
ax.legend(ax.get_lines(), df.columns, loc='best', ncol=2)
plt.tight_layout()
该图现在看起来像:
关于python - 在 Python 中,如何创建基于 groupby() 的两个类别的线图,其中一个类别是图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51034291/