如何创建“点图"在 Matplotlib 中?(不是散点图) [英] How to create a "dot plot" in Matplotlib? (not a scatter plot)
问题描述
我想创建我的统计书所称的点状图",其中图中的点数等于观测值的数目.这是来自
在该示例中,X轴上 0
值上方有六个点,表示六个观测值零.
似乎点状图"可以有几种变体.在查找如何使用Matplotlib进行创建时,我只遇到了一个散点图,即一个数据点,该数据点表示X和Y值之间的关系.
我要使用Matplotlib创建的情节类型可能吗?
假设您有一些数据会产生如下所示的直方图,
import numpy as np;np.random.seed(13)导入matplotlib.pyplot作为plt数据= np.random.randint(0,12,size = 72)plt.hist(data, bins=np.arange(13)-0.5, ec="k")plt.show()
您可以通过计算直方图并绘制所有可能点的散点图来创建点图,如果点的颜色超过直方图给出的数字,则点的颜色为白色.
import numpy as np;np.random.seed(13)导入matplotlib.pyplot作为plt数据= np.random.randint(0,12,size = 72)bins = np.arange(13)-0.5hist,edges = np.histogram(data, bins=bins)y = np.arange(1,hist.max()+ 1)x = np.arange(12)X,Y = np.网格(x,y)plt.scatter(X,Y, c=Y<=hist, cmap="Greys")plt.show()
或者,您可以将不需要的点设置为 nan
,
Y = Y.astype(np.float)Y[Y>hist] = np.nanplt.scatter(X,Y)
I'd like to create what my statistics book calls a "dot plot" where the number of dots in the plot equals the number of observations. Here's an example from mathisfun.com:
In the example, there are six dots above the 0
value on the X-axis representing the six observations of the value zero.
It seems that a "dot plot" can have several variations. In looking up how to create this with Matplotlib, I only came across what I know of as a scatter plot with a data point representing the relationship between the X and Y value.
Is the type of plot I'm trying to create possible with Matplotlib?
Supoose you have some data that would produce a histogram like the following,
import numpy as np; np.random.seed(13)
import matplotlib.pyplot as plt
data = np.random.randint(0,12,size=72)
plt.hist(data, bins=np.arange(13)-0.5, ec="k")
plt.show()
You may create your dot plot by calculating the histogram and plotting a scatter plot of all possible points, the color of the points being white if they exceed the number given by the histogram.
import numpy as np; np.random.seed(13)
import matplotlib.pyplot as plt
data = np.random.randint(0,12,size=72)
bins = np.arange(13)-0.5
hist, edges = np.histogram(data, bins=bins)
y = np.arange(1,hist.max()+1)
x = np.arange(12)
X,Y = np.meshgrid(x,y)
plt.scatter(X,Y, c=Y<=hist, cmap="Greys")
plt.show()
Alternatively you may set the unwanted points to nan
,
Y = Y.astype(np.float)
Y[Y>hist] = np.nan
plt.scatter(X,Y)
这篇关于如何创建“点图"在 Matplotlib 中?(不是散点图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!