我正在尝试创建一个散点图,其中每个x轴类别标签包含两个数据点(来自不同的条件),并以显示两者之间趋势的方式显示。使用以下代码,我设法将每个x轴类别标签与其指定的数据点进行匹配。
import numpy as np
import matplotlib.pyplot as plt
import csv
# x-axis labels
IDs = ['a', 'b', 'c', 'd', 'e', 'f']
# y-axis data
lowCont = [-0.31, 0.71, 0.37, 0.05, 0.15, 1.33]
highCont = [-0.38, -0.16, 0.02, -0.55, -0.02, -0.51]
# Standard Errors for each data point
lowContErr = [0.03,0.13,0.02,0.10,0.09,0.04]
highContErr = [0.07, 0.09, 0.03, 0.09, 0.06, 0.03]
# plotting
plt.scatter(range(len(lowCont)), lowCont, color = 'r', label = 'label1')
plt.scatter(range(len(highCont)), highCont, color = 'k', label = 'label2')
plt.xticks(range(len(lowCont)), IDs, size='small')
plt.errorbar(range(len(lowCont)), lowCont,yerr=lowContErr, linestyle="None", color = 'r')
plt.errorbar(range(len(highCont)), highCont,yerr = highContErr,linestyle = "None", color = 'k')
plt.xlabel('x')
plt.ylabel('y')
plt.title('graph title')
plt.legend()
plt.show()
但是,我在这里要确定的是突出显示每个x轴标签的两个数据点之间的趋势(增加或减少)。为此,我需要并排显示数据点的耦合(而不是在单个垂直轴上的每个顶部)。以下是一个x轴标签所需图表的示例:
我想我的思维模式指示我为x轴类别(例如,0,1)创建虚拟 sub x轴类别,并将数据点分配给它们,但我的技能在python和matplotlib不足以满足我的目标。
答案 0 :(得分:1)
您可以通过将highCont
沿x轴移动一定量,然后使用plt.plot()
在它们之间绘制线条来实现此目的。
在下面的示例中,我使用变量shift
将x轴上的highCont
值移动了0.2。
您可以使用plt.errorbar()
的capsize
参数为您的误差线(包含在所需图像中)添加上限,如果未提供,则默认为None
。
import matplotlib.pyplot as plt
import numpy as np
IDs = ['a', 'b', 'c', 'd', 'e', 'f']
lowCont = [-0.31, 0.71, 0.37, 0.05, 0.15, 1.33]
highCont = [-0.38, -0.16, 0.02, -0.55, -0.02, -0.51]
lowContErr = [0.03,0.13,0.02,0.10,0.09,0.04]
highContErr = [0.07, 0.09, 0.03, 0.09, 0.06, 0.03]
shift = 0.2 # Change this to increase distance between pairs of points
x_vals = np.arange(0,len(lowCont),1)
shifted_x_vals = np.arange(0+shift,len(highCont)+shift,1)
# loop through the data and plot the pairs of points to join them by a line
for x,x1,y,y1 in zip(x_vals,shifted_x_vals,lowCont,highCont):
plt.plot([x,x1], [y,y1], color="k")
plt.scatter(x_vals, lowCont, color = 'r', label = 'label1')
plt.scatter(shifted_x_vals, highCont, color = 'k', label = 'label2')
# set ticks to between the two points
plt.xticks(x_vals + (shift/2), IDs, size='small')
plt.errorbar(x_vals, lowCont,yerr=lowContErr, linestyle="None", color = 'r', capsize=3)
plt.errorbar(shifted_x_vals, highCont,yerr = highContErr,linestyle = "None", color = 'k', capsize=3)
plt.xlabel('x')
plt.ylabel('y')
plt.title('graph title')
plt.legend()
plt.show()
哪个给出了