简体   繁体   中英

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. This is happening only when I have a high amount of bars to display (>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:

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.

It is just the problem of resolution. Since you are adding so many dataPoints (400 in your case), you are creating too many bins!! This makes it overlap in the default plot that is generated.

The default barchart plot with 200 dataPoints looks like this

在此处输入图片说明

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 .

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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