matplotlib: box plot for each category

帅比萌擦擦* 提交于 2019-12-24 00:17:32

问题


My pandas data frame has two columns: category and duration. And I use the following code to make a box plot of all data points.

import matplotlib.pyplot as plt
plt.boxplot(df.duration)
plt.show()

However, if I want one box fore each category, how do I modify the above code? Thanks!


回答1:


We can do it with pandas

#df=pd.DataFrame({'category':list('aacde'),'duration':[1,3,2,3,4]}) sample data
df.assign(index=df.groupby('category').cumcount()).pivot('index','category','duration').plot(kind='box')




回答2:


In addition to Wen's answer, which is spot on, you might want to check out the seaborn library. It was made to do this kind of plot.

Seaborn is a Python visualization library based on matplotlib. It provides a high-level interface for drawing attractive statistical graphics.

Check the documentation for boxplots

Draw a box plot to show distributions with respect to categories.

sns.boxplot(data=df, x='category', y='duration')



来源:https://stackoverflow.com/questions/48712274/matplotlib-box-plot-for-each-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!