我正在try 在matplotlib中创建一个曲线图,其中我对两个数据集应用了两个方法, for each 数据集更改了拟合类型,这样我就有了8个数据结果点.

这是我目前拥有的代码:

n_groups = 4
means_type1 = (10,20,10,15)
means_type2 = (20,30,15,10)

# create plot
fig, ax = plt.subplots()
plt.grid(which='major', color='#EEEEEE', linewidth=0.5,zorder=0)
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, means_type1, bar_width,
alpha=1,
color='blue',
label='Type 1',zorder=3)

rects2 = plt.bar(index + bar_width, means_type2, bar_width,
alpha=1,
color='green',
label='Type 2',zorder=3)

plt.ylabel('Metric')
plt.xticks(index + bar_width, ('Dataset 1', 'Dataset 2', 'Dataset 1', 'Dataset 2'))
plt.legend()
plt.figtext(0.4,0.01, "Method 1", ha="center", va="center",fontsize=7)
plt.figtext(0.77,0.01, "Method 2", ha="center", va="center",fontsize=7)

plt.tight_layout()
plt.show()

它会生成绘图:

Attempt

剧情主要是我想要的,但有两个关键的改变我似乎不能做:

  • 数据集的标签没有居中-它们只围绕类型2居中.x轴刻度也是如此.
  • 方法标签没有居中,我将它们大致放在中间.
  • 我想要一些方法来区分这两种方法.就像一条垂直线,从x轴向下,把它分成两部分.

推荐答案

  • 刻度对齐:在bar中设置align='edge'.
  • 标签对齐方法:使用annotate为x和y位置放置具有不同坐标系的标签.在这里,我使用数字分数表示y值,以使其与您从plt.figtext获得的值一致,但使用数据坐标表示x值.
  • 垂直线:使用ax.vline.

请注意,在bar中设置了align='edge'之后,蓝色条的左边缘的值为index.因此,行和"方法"批注比x方向少0.15.

import matplotlib.pyplot as plt
import numpy as np

n_groups = 4
means_type1 = (10,20,10,15)
means_type2 = (20,30,15,10)

# create plot
fig, ax = plt.subplots()
plt.grid(which='major', color='#EEEEEE', linewidth=0.5,zorder=0)
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, means_type1, bar_width,
alpha=1,
color='blue',
label='Type 1',zorder=3, align='edge')

rects2 = plt.bar(index + bar_width, means_type2, bar_width,
alpha=1,
color='green',
label='Type 2',zorder=3, align='edge')

ax.axvline(index[2] - 0.15, color='gray', linestyle='dashed')

plt.ylabel('Metric')
plt.xticks(index + bar_width, ('Dataset 1', 'Dataset 2', 'Dataset 1', 'Dataset 2'))
plt.legend()
ax.annotate("Method 1", (index[1] - 0.15, 0.01), xycoords=('data', 'figure fraction'), ha="center", va="center",fontsize=7)
ax.annotate("Method 2", (index[3] - 0.15, 0.01), xycoords=('data', 'figure fraction'), ha="center", va="center",fontsize=7)

plt.tight_layout()
plt.show()

enter image description here

Python相关问答推荐

如何在句子之间添加空白但忽略链接?

Pandas或pyspark跨越列创建

pandas MultiIndex是SQL复合索引的对应物吗?

在for循环中保存和删除收件箱

在Python中根据id填写年份系列

Pandas read_jsonfuture 警告:解析字符串时,to_datetime与单位的行为已被反对

在编写要Excel的数据透视框架时修复标题行

多处理代码在while循环中不工作

如何在BeautifulSoup中链接Find()方法并处理无?

根据条件将新值添加到下面的行或下面新创建的行中

Pystata:从Python并行运行stata实例

将特定列信息移动到当前行下的新行

如何检测背景有噪的图像中的正方形

Pandas 滚动最接近的价值

在极性中创建条件累积和

导入...从...混乱

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

AES—256—CBC加密在Python和PHP中返回不同的结果,HELPPP

寻找Regex模式返回与我当前函数类似的结果

如何使用OpenGL使球体遵循Python中的八样路径?