Python 无法获得直方图以显示带有垂直线的分隔箱
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42542252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot get histogram to show separated bins with vertical lines
提问by Canuck
Annoying strange problem and I have not been able to find a solution on this site yet (although the question has popped up)
恼人的奇怪问题,我还没有在这个网站上找到解决方案(虽然问题已经出现)
I am trying to make a histogram where the bins have the 'bar style' where vertical lines separate each bin but no matter what I change the histtype constructor to I get a step filled histogram.
我正在尝试制作一个直方图,其中 bin 具有“条形样式”,其中垂直线将每个 bin 分开,但无论我如何更改 histtype 构造函数,我都会得到一个阶梯填充直方图。
Here is my code. Note I am using jupyter notebook installed via anaconda with python version 2.7.6
这是我的代码。注意我使用的是通过 anaconda 安装的 jupyter notebook,python 版本为 2.7.6
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand((100))
bins = np.linspace(0, 2, 40)
plt.title('Relative Amplitude',fontsize=30)
plt.xlabel('Random Histogram')
plt.ylabel('Frequency',fontsize=30)
plt.hist(x, bins, alpha=0.5, histtype='bar')
plt.legend(loc='upper right',fontsize=30)
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
plt.show()
Thats it and I get a step filled diagram with no vertical lines separating the bars. What is annoying is that I didn't have this problem awhile ago, something clearly has changed and I don't know what.I have tried histype='barstacked' as well. Thank you kindly for your help
就是这样,我得到了一个阶梯填充图,没有分隔条的垂直线。令人讨厌的是,我前一阵子没有遇到这个问题,显然发生了一些变化,我不知道是什么。我也尝试过 histype='barstacked'。非常感谢您的帮助
回答by ngoldbaum
Using your example:
使用您的示例:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.rand((100))
bins = np.linspace(0, 2, 40)
plt.title('Relative Amplitude',fontsize=30)
plt.xlabel('Random Histogram')
plt.ylabel('Frequency',fontsize=30)
plt.hist(x, bins, alpha=0.5, histtype='bar', ec='black')
plt.legend(loc='upper right',fontsize=30)
plt.xticks(fontsize = 20)
plt.yticks(fontsize = 20)
plt.show()
Which produces the following image:
产生以下图像:
The key difference is the use of the ec
keyword argument. This is short for "edgecolor". In the documentation for plt.hist
it says that in addition to all of the listed keyword arguments, plt.hist
also takes keyword arguments for the Patch
initializer. edgecolor
is one of those keyword arguments. That's why it's not explicitly listed in the documentation for plt.hist
. All of the bars in the plot are an individual Patch
object, so you're saying you want all of the bars to be drawn with a black outline (or edgecolor
in matplotlib jargon).
主要区别在于ec
关键字参数的使用。这是“edgecolor”的缩写。在plt.hist
它的文档中说,除了所有列出的关键字参数外,plt.hist
还为Patch
初始值设定项采用关键字参数。edgecolor
是这些关键字参数之一。这就是为什么它没有在plt.hist
. 图中的所有条形都是一个单独的Patch
对象,因此您是说希望所有条形都用黑色轮廓(或edgecolor
matplotlib 行话)绘制。