简体   繁体   English

如何使用matplotlib正确绘制条形图?

[英]How to properly plot bar chart with matplotlib?

I have a script which takes the articles on my website, and associated traffic data such as page views, average time on page etc from Google Analytics and places them into a pandas DataFrame. 我有一个脚本,可将网站上的文章以及来自Google Analytics(分析)的相关访问量数据(如页面浏览量,平均页面停留时间等)收集到pandas DataFrame中。

I would like to plot the best 5 performing pages as bar chart however the bar plots aren't graphing properly. 我想将效果最好的5个页面绘制为条形图,但是条形图无法正确绘制。

The script successfully grabs the GA data and places it into a DataFrame so i'm able to do all my analysis but it fails to properly build a bar plot as shown in the image. 该脚本成功获取了GA数据并将其放入DataFrame中,因此我能够进行所有分析,但是它无法正确构建如图所示的条形图。

In this example, i've replaced the page names with numbers 1-5 and the page views data is as shown: 在此示例中,我将页面名称替换为数字1-5,页面浏览量数据如下所示:

['3881', '3707', '2269', '1950', '1812', '1734'] ['3881','3707','2269','1950','1812','1734']

As we can see in the image the bars aren't correctly representing the values. 正如我们在图像中看到的,条形图未正确表示值。

在此处输入图片说明

import pandas as pd
import matplotlib.pyplot as plt

#[GA code is here but deleted for simplicity]

x = ["0", "1","2","3","4","5"]
y = ['3881', '3707', '2269', '1950', '1812', '1734']

plt.bar(x,y,label="Bars 1",color="black")

plt.xlabel("X")
plt.ylabel("Y")
plt.title("Bar")
plt.legend()
plt.show()

One would expect a bar plot where the values decrease starting from 3881 down to 1734 with each individual bar correctly drawn. 人们会期望一种条形图,其中值从3881开始下降到1734,并且正确绘制了每个条形。 Instead, we get a graph where the first bar is zero and it increases, contradicting the values on the axis. 取而代之的是,我们得到一个图形,其中第一个条形为零,并且它增加了,与轴上的值相反。

You are plotting your data as strings. 您正在将数据绘制为字符串。 Change y to be integers and I think you'll get what you expect y更改为整数,我想您会得到期望的结果

条形图

Something like: 就像是:

plt.bar(x, [int(i) for i in y], label="Bars 1", color="black")

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM