简体   繁体   English

如何使用 matplotlib.pyplot 在 x 轴上创建分组条形图(按月和年)并在 y 轴上创建值?

[英]How to create a grouped bar chart (by month and year) on the x-axis and values on the y-axis using matplotlib.pyplot?

This is my dataframe:这是我的 dataframe:

   Year  Month    Views
0  2016      5    97162
1  2016      6   415627
2  2016      7   675071
3  2016      8   962525
4  2016      9  1244306

I want the views to be plotted on the y-axis, and on the x-axis I want the months and years like this:我希望将视图绘制在 y 轴上,而在 x 轴上我希望月份和年份如下所示: 像这样 . . How can I visualize my dataframe like the above figure using matplotlib.pyplot?如何使用 matplotlib.pyplot 可视化我的 dataframe,如上图所示?

Use with DataFrame.pivot with DataFrame.plot.bar :DataFrame.pivotDataFrame.plot.bar一起使用:

df.pivot('Year','Month','Views').plot.bar()

If need month names add rename after pivoting:如果需要月份名称,请在旋转后添加rename

month_dict = {1 : "January", 2 : "February", 3 : "March", 4 : "April", 
              5 : "May" , 6 : "June", 7 : "July", 8 : "August", 
              9 : "September", 10 : "October" ,11 : "November",12 : "December"}

df.pivot('Year','Month','Views').rename(columns=month_dict).plot.bar()

You can simply use seaborn instead.您可以简单地使用seaborn代替。 It's nicer in coloring, and easier to use, most of the times.在大多数情况下,它的着色效果更好,而且更易于使用。

For example:例如:

import pandas as pd
import seaborn as sns

df = pd.DataFrame({"year": [1,1,1,1,2,3,2,3,2,3],
                   "month": [4, 6, 7, 5, 4, 6, 7, 1, 1, 4],
                   "value": list(range(5,15))})


sns.barplot(data=df, y='value', x='year', hue='month')

The output is as follows: output如下:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用正确的标签将值从 x 轴切换到 y 轴(Python Matplotlib.pyplot 或 Seaborn) - Switch the values from x-axis to y-axis while using the correct labels(Python Matplotlib.pyplot OR Seaborn) 使用matplotlib.pyplot为我的x轴指定值? - Specifying values for my x-axis using the matplotlib.pyplot? 如何用pyplot在相同的x轴(日期时间)但不同的y轴上绘制线形图和条形图? - How to plot line and bar-chart on the same x-axis (datetime) but different y-axis with pyplot? python - 如何在x轴上的值范围上制作条形图并计算y轴上的范围? - How to make a bar chart on range of values on x-axis and count on the range on y-axis in python? 使用 Seaborn 或 Matplotlib 生成折线图,其中:年为色调,月为 X 轴,浮点列为 Y 轴 - Generating a Line Graph using Seaborn or Matplotlib with: Year as hue, Month as X-Axis and Float Column as Y-Axis 如何使用 Python 库 matplotlib.pyplot 在 Y 轴上设置值差距 - How to set value gap on Y-axis using Python library matplotlib.pyplot 堆叠条形图交换 x 轴和 y 轴 - Stacked bar chart swap x-axis and y-axis 如何在 matplotlib.pyplot 中设置 X 和 Y 轴标题 - How to set X and Y axis Title in matplotlib.pyplot Plot 具有不同的 x 轴和 y 轴使用 matplotlib - Plot with different x-axis and y-axis using matplotlib 如何在matplotlib中均衡x轴和y轴的比例? - How to equalize the scales of x-axis and y-axis in matplotlib?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM