python - 在 Python 中,如何创建基于 groupby() 的两个类别的线图,其中一个类别是图例?

标签 python matplotlib

我使用此代码对平均值进行分组。按年份和大陆划分的预期生命周期:

avg_lifeExp_by_cont_yr = df.groupby(['year','continent'])['lifeExp'].mean()

结果如下所示:

screenshot

我想创建一个折线图,在 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()

数据处理有几个技巧,请查看代码中的注释。粗略的情节看起来像
plot of the results

请用更多的 matplotlib 操作润色你的图。例如:
  • 设置 y 标签
  • 两个大的高度,将图例设置为两列以减少它
  • 线条的颜色或线条的形状
  • 线与标记?

  • 这里有一些调整
    # 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()
    

    该图现在看起来像:
    tweaked figure

    关于python - 在 Python 中,如何创建基于 groupby() 的两个类别的线图,其中一个类别是图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51034291/

    相关文章:

    python - 在 metpy 中转换为相对于地球和相对于网格的流矢量

    python - Django tastypie 包括通用外键字段结果

    python - 从 Jupyter Notebook 复制数据

    datetime - y 轴上的 Matplotlib 日期

    python - 定义要在 Scatter.plot 中调用的函数

    python - Python 类的最大方法数是多少?

    python - 如何在查询 Python 中按名称获取字段?

    python - seaborn:默认情况下绝望图

    python - Cartopy:使用散点数据渲染图层的顺序

    python - 如何通过 pandas dataframe axis python 获取条形图