简体   繁体   English

Python:matplotlib条形图的奇怪行为

[英]Python : strange behavior with matplotlib barchart

I have a strange behavior using matplotlib in an ipython notebook: when I change the attribute "color" of the barchart, the result is ugly, I have some bars in red and some others in black. 我在ipython笔记本中使用matplotlib有一个奇怪的行为:当我更改条形图的“颜色”属性时,结果很难看,我的条形为红色,另一些条形为黑色。 This is happening only when I have a high amount of bars to display (>100). 仅当我要显示大量条形图(> 100)时,才会发生这种情况。

You can execute the code below to reproduce the problem, playing with the dataPoints parameter to see the effect of the number of bars: 您可以执行以下代码来重现该问题,并使用dataPoints参数查看条形数量的影响:

import random
import matplotlib.pyplot as plt

dataPoints = 400
data = random.sample(range(300, 1000), dataPoints)
xCoords = range(dataPoints)

fig = plt.figure(figsize=[13,9])
plt.bar(xCoords,data,color='red')
plt.show()

Here is an example of the result : 这是结果的示例:

产量

It is not the problem of pyplot, nor is it the problem in your code or your version of iPython. 这不是pyplot的问题,也不是您的代码或iPython版本中的问题。

It is just the problem of resolution. 这只是解决问题。 Since you are adding so many dataPoints (400 in your case), you are creating too many bins!! 既然你要添加这么多的dataPoints (400你的情况),您创建了太多箱! This makes it overlap in the default plot that is generated. 这使其在生成的默认图中重叠。

The default barchart plot with 200 dataPoints looks like this 默认的200个数据点的dataPoints如下所示

在此处输入图片说明

But when you zoom in to take a look, you can see that your bins are actually seperated and the black lines are now not clearly visible. 但是,当您放大看一下时,您会看到您的垃圾箱实际上是分开的,黑线现在也不清楚。

在此处输入图片说明

The above is the same execution of your program with 200 dataPoints . 上面是您的程序具有200个dataPoints的相同执行。

If you zoom in on the bars, you will see that actually, there are no black bars. 如果放大这些条,您会发现实际上没有黑条。 The black you see is the result of the black border around the bars and interpolation to fit the pixels of your screen. 您看到的黑色是条形周围的黑色边框和内插以适合屏幕像素的结果。

What you can do to have only red in your image is changing the color of the border to red using 您可以做的是仅在图像中使用红色,这是使用以下方法将边框的颜色更改为红色

plt.bar(xCoords, data, color='red', edgecolor='red')

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

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