如何通过pandas groupby绘制条形图,然后循环获取所有唯一值 [英] How to plot a barchart by pandas groupby and then loop for all unique values
问题描述
我有以下数据,其中包含人员姓名、分数和尝试次数:
I have the following data which has a persons name, score and what attempt number it was:
# Import pandas library
import pandas as pd
import numpy as np
# Data
data = [['tom', 10,1], ['nick', 15,1], ['dom', 14,1], ['tom', 15,2], ['nick', 18,2], ['dom', 15,2], ['tom', 17,3]
, ['nick', 14,3], ['tom',16 ,4], ['dom', 22,3]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['Name', 'Score','Attempt'])
# print dataframe.
df
Name Score Attempt
0 tom 10 1
1 nick 15 1
2 dom 14 1
3 tom 15 2
4 nick 18 2
5 dom 15 2
6 tom 17 3
7 nick 14 3
8 tom 16 4
9 dom 22 3
我希望为每个唯一的 Name
绘制一个 seaborn 水平条形图
,其中 Score
作为值,轴作为 Attempt
编号(类别),然后创建一个循环,以便为每个人生成一个 3 页的 PDF.我不太明白的是如何:
I am hoping to plot a seaborn horizontal bar plot
for each unique Name
which has Score
as the value and the axis as the Attempt
number (category) and then create a loop so that it produces a 3 page PDF for each person. What I don't quite understand is how to:
a) 按 groupby 绘制 - 我是否需要制作多个切片数据框?
a) plot by a groupby - do i need to make multiple sliced dataframes?
b) 循环生成 PDF 的多个页面.
b) make it in a loop to produced multiple pages for a PDF.
任何帮助将不胜感激!谢谢!
Any help would be much appreciated! Thanks!
推荐答案
这是一个循环,用于将每个名称的数据绘制为单独的图形:
Here is a loop to plot the data for each name as a separate graph:
plt.style.use('seaborn')
for name in df['Name'].unique():
fig, ax = plt.subplots()
sub = df[df.Name == name]
sns.barplot(y='Attempt',x='Score',data=sub, orient='h', ax=ax)
ax.set_title(name.capitalize())
三个图之一:
我会将您问题的 PDF 部分移到一个新帖子中,因为您的要求有点含糊(什么会填满 3 页?),而且这似乎是与制作情节不同的问题.
I would move the PDF part of your question to a new post, as it is kind of vague what your are asking for (what's going to fill 3 pages?), and it seems like a separate issue from making the plots.
但请注意,您可以将图表直接保存为(1 页)PDF:
But note that you can save graphs straight into a (1-page) PDF:
#in the loop
fig.savefig(name+'.pdf')
这篇关于如何通过pandas groupby绘制条形图,然后循环获取所有唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!