如何绘制离散线而不是条形图?

时间:2019-08-13 11:31:18

标签: python numpy matplotlib

我已经绘制了一个直方图。但是我想绘制离散线而不是三个条。有什么办法吗?

import matplotlib.pyplot as plt
w1 = [-2,-2,-2,-2,0,0,0,1,1,1,1,1,1]
n,bins,patches = plt.hist(w1,bins=10)
plt.xlabel("bins")
plt.ylabel("counts")
plt.show()

3 个答案:

答案 0 :(得分:1)

如果您只想绘制宽度较小的条形图

使用参数rwidth来表示每个直方图条相对于bin大小的相对宽度。实验不同的值以获得不同的视觉效果。示例:

w1=[-2,-2,-2,-2,0,0,0,1,1,1,1,1,1] 
n,bins,patches=plt.hist(w1,bins=10, rwidth=0.1) 
plt.xlabel("bins") 
plt.ylabel("counts") 
plt.show()

enter image description here

如果您实际上想绘制线条而不是条形图

w1内的每个值都放在上方,并在从XY(值,0)到XY(值,值在plt.plot中出现的行)上调用w1。示例:

for value in w1: 
    plt.plot([value, value], [0, w1.count(value)], color='b') 
plt.show() 

enter image description here

请注意,我使用了参数color='b',以便matplotlib不会为每行设置不同的颜色。另外,默认情况下,当我们调用plt.plot时,matplotlib会在周围的线条上添加一些空格,因此您可能要调用plt.ylim(bottom=0),以使这些条形看起来不会在图形上方“浮动”。

答案 1 :(得分:0)

plt.hist(...)广告中,变量rwidth(相对宽度)的值为1,这样您将获得宽度较小的条形。

在此处详细了解:https://matplotlib.org/api/_as_gen/matplotlib.pyplot.hist.html#matplotlib.pyplot.hist

答案 2 :(得分:0)

我建议使用带有数据唯一元素计数的词干图。当然,这仅对离散数据有意义。

import numpy as np
import matplotlib.pyplot as plt

w1 = [-2,-2,-2,-2,0,0,0,1,1,1,1,1,1]
u, c = np.unique(w1, return_counts=True)
plt.stem(u,c, use_line_collection=True, basefmt="none")
plt.ylim(0,None)
plt.xlabel("bins")
plt.ylabel("counts")
plt.show()

this answer