通过 matplotlib 和 seaborn 将 pandas groupby 转换为图表
Posted
技术标签:
【中文标题】通过 matplotlib 和 seaborn 将 pandas groupby 转换为图表【英文标题】:pandas groupby to charts via matplotlib and seaborn 【发布时间】:2020-08-16 22:52:43 【问题描述】:如何将单个图表(趋势线)中的以下数据转换为名称
name month
x April 80.0
February 88.0
January 82.0
March 48.0
y April 77.0
February 76.0
January 80.0
March 82.0
z April 86.0
February 81.0
January NaN
March 85.0
【问题讨论】:
【参考方案1】:使用Series.unstack
进行整形,然后将列转换为CategoricalIndex
并排序以获得正确的顺序,最后按DataFrame.plot
绘制:
months = ['January','February','March','April',
'May','June','July','August',
'September','October','November','December']
#your groupby code
#s = df.groupby(...)
df = s.unstack()
df.columns = pd.CategoricalIndex(df.columns, ordered=True, categories=months)
df = df.sort_index(axis=1)
print (df)
month January February March April
name
x 82.0 88.0 48.0 80.0
y 80.0 76.0 82.0 77.0
z NaN 81.0 85.0 86.0
如果想要交换列和索引值:
months = ['January','February','March','April',
'May','June','July','August',
'September','October','November','December']
#your groupby code
#s = df.groupby(...)
df = s.unstack(0)
df.index = pd.CategoricalIndex(df.index, ordered=True, categories=months)
df = df.sort_index()
print (df)
name x y z
month
January 82.0 80.0 NaN
February 88.0 76.0 81.0
March 48.0 82.0 85.0
April 80.0 77.0 86.0
df.plot()
【讨论】:
以上是关于通过 matplotlib 和 seaborn 将 pandas groupby 转换为图表的主要内容,如果未能解决你的问题,请参考以下文章
将 Matplotlib/Seaborn 散点图变形为平行四边形
使用 seaborn 或 matplotlib 分组箱线图的数据格式
使用 Seaborn 和 Matplotlib 在热图和线图的共享子图中对齐 x 轴刻度