[英]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
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. 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) plot by a groupby - do i need to make multiple sliced dataframes? a)plot by groupby - 我需要制作多个切片数据帧吗?
b) make it in a loop to produced multiple pages for a PDF. b) 使其循环生成 PDF 的多个页面。
Any help would be much appreciated!任何帮助将非常感激! Thanks!谢谢!
Here is a loop to plot the data for each name as a separate graph:这是一个循环到 plot 每个名称的数据作为单独的图表:
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())
One of the three plots:三个地块之一:
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.我会将您问题的 PDF 部分移至新帖子,因为您的要求有点模糊(什么会填满 3 页?),这似乎是与制作情节不同的问题。
But note that you can save graphs straight into a (1-page) PDF:但请注意,您可以将图形直接保存到(1 页)PDF 中:
#in the loop
fig.savefig(name+'.pdf')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.