如何使用python // Matplotlib重新创建此图形?

Hee*_*bes 5 python plot matplotlib

我想重新创建这样的东西:

但使用我自己的数据 我的数据如下所示:

 Number    Name1        Structure        mean    stdev
 1         Aldehydes    RCH=O       122.76    7.67
 2         Ketones          R2C=O       8.11      0.15
 2         Amides       R-CONr2     20.1      83.24
Run Code Online (Sandbox Code Playgroud)

如何重新创建该图?我得到了:

from pylab import *
import numpy  
data = numpy.genfromtxt('data',unpack=True,names=True,dtype=None) 
pos = arange(size(data['Number']))
ax2.errorbar(pos,data['mean'], yerr=data['stdev'])
Run Code Online (Sandbox Code Playgroud)

但是我无法得到与我的例子相似的情节。有人可以为此发布示例代码吗?

gca*_*tes 1

您可以首先将数据绘制为误差线,并用相应的文本对其进行注释。

下面是一个简单的代码供您开始:

import numpy as np
import matplotlib.pyplot as plt

data = np.genfromtxt('data.txt', unpack=True,names=True,dtype=None)

fig, ax = plt.subplots()
ax.set_yticklabels([])
ax.set_xlabel(r'ppm ($\delta$)')
pos = np.arange(len(data))
#invert y axis so 1 is at the top
ax.set_ylim(pos[-1]+1, pos[0]-1)
ax.errorbar(data['mean'], pos, xerr=data['stdev'], fmt=None)

for i,(name,struct) in enumerate(zip(data['Name1'], data['Structure'])):
    ax.text(data['mean'][i], i-0.06, "%s, %s" %(name, struct), color='k', ha='center')

plt.show()
Run Code Online (Sandbox Code Playgroud)

图像

更改注释中单个字母的颜色将非常棘手,因为 matplotlib 不支持多色文本。我尝试通过使用正则表达式来注释两次相同的文本(一个仅带有红色的“C”,一个没有“C”)来找到解决方法,但因为每个字母不占用相同的空间,所以它不会对于所有单词都效果很好(见下文)。

#add to the import
import re

#and change
for i,(name,struct) in enumerate(zip(data['Name1'], data['Structure'])):
    text_b = ax.text(data['mean'][i], i-0.05, "%s, %s" %(name, struct), color='k', ha='center')
    text_b.set_text(text_b.get_text().replace('C', '   '))
    text_r = ax.text(data['mean'][i], i-0.05, "%s %s" %(name, struct), color='r', ha='center')
    text_r.set_text(re.sub('[abd-zABD-Z]', '  ', text_r.get_text()))
    text_r.set_text(re.sub('[0-9\=\-\W]', ' ', text_r.get_text()))
Run Code Online (Sandbox Code Playgroud)

图像2