Python 在图形上绘制单个点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15382887/
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
Plotting single points on a graph
提问by The Unfun Cat
I have a violin plot which looks like this:
我有一个小提琴图,看起来像这样:


I want to plot a few individual dots (or lines, crosses, points whichever is easiest) on each x-value, on top of the violins, like this:
我想在小提琴顶部的每个 x 值上绘制几个单独的点(或线、十字、点,以最简单的为准),如下所示:


How do I go about doing this?
我该怎么做?
This is the code for making the violin plots (see Violin Plot with Matplotlib)
这是制作小提琴图的代码(请参阅带有 Matplotlib 的小提琴图)
from matplotlib.pyplot import figure, show
from scipy.stats import gaussian_kde
from numpy.random import normal
from numpy import arange
def violin_plot(ax, data, pos, bp=False):
'''
create violin plots on an axis
'''
dist = max(pos)-min(pos)
w = min(0.15*max(dist,1.0),0.5)
for d,p in zip(data,pos):
k = gaussian_kde(d) #calculates the kernel density
m = k.dataset.min() #lower bound of violin
M = k.dataset.max() #upper bound of violin
x = arange(m,M,(M-m)/100.) # support for violin
v = k.evaluate(x) #violin profile (density curve)
v = v/v.max()*w #scaling the violin to the available space
ax.fill_betweenx(x,p,v+p,facecolor='y',alpha=0.3)
ax.fill_betweenx(x,p,-v+p,facecolor='y',alpha=0.3)
if bp:
ax.boxplot(data,notch=1,positions=pos,vert=1)
if __name__=="__main__":
pos = range(5)
data = [normal(size=100) for i in pos]
fig=figure()
ax = fig.add_subplot(111)
violin_plot(ax,data,pos,bp=1)
fig.savefig("violins.gif")
采纳答案by David Zwicker
Just plot the extra data right after the other plot:
只需在另一个图之后立即绘制额外的数据:
from matplotlib.pyplot import figure, show
from scipy.stats import gaussian_kde
from numpy.random import normal
from numpy import arange
def violin_plot(ax, data, pos, bp=False):
'''
create violin plots on an axis
'''
dist = max(pos)-min(pos)
w = min(0.15*max(dist,1.0),0.5)
for d,p in zip(data,pos):
k = gaussian_kde(d) #calculates the kernel density
m = k.dataset.min() #lower bound of violin
M = k.dataset.max() #upper bound of violin
x = arange(m,M,(M-m)/100.) # support for violin
v = k.evaluate(x) #violin profile (density curve)
v = v/v.max()*w #scaling the violin to the available space
ax.fill_betweenx(x,p,v+p,facecolor='y',alpha=0.3)
ax.fill_betweenx(x,p,-v+p,facecolor='y',alpha=0.3)
if bp:
ax.boxplot(data,notch=1,positions=pos,vert=1)
if __name__=="__main__":
pos = range(5)
data = [normal(size=100) for i in pos]
fig=figure()
ax = fig.add_subplot(111)
violin_plot(ax,data,pos,bp=1)
data_x = [0, 1, 2, 2, 3, 4]
data_y = [1.5, 1., 0.7, 2.5, 1, 1.5]
ax.plot(data_x, data_y, 'or')
fig.savefig("violins.gif")
which gives
这使



