对于这种类型的图,我认为最耗时的类型是 MPL,但我编写代码的方式是模仿预期输出的第二个示例。基本上,它是用箭头和注释创建的。
import pandas as pd
import numpy as np
import io
data = '''
Party 2009 2013
CDU/CSU 33.8 41.5
SPD 23.0 25.7
LINKE 11.9 8.6
GRÜNE 10.7 8.4
FDP 14.6 4.8
'''
df = pd.read_csv(io.StringIO(data), delim_whitespace=True)
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
colors = mcolors.TABLEAU_COLORS
fig, ax = plt.subplots(figsize=(10,4))
plt.rcParams.update({'axes.spines.top': False, 'axes.spines.right': False})
for (idx,row), c in zip(df.iterrows(),colors):
cols = colors.keys()
ax.arrow(row['2009'], idx, row['2013']-row['2009'], 0, head_width=0.2, head_length=0.7, width=0.03, fc=c, ec=c)
if row['2009'] < row['2013']:
ax.annotate('{}'.format(row['2009']), xy=(row['2009'], idx), xytext=(row['2009']-2.5,idx-0.05), xycoords='data', color=c)
ax.annotate('{}'.format(row['2013']), xy=(row['2013'], idx), xytext=(row['2013']+0.9,idx-0.05), xycoords='data', color=c)
else:
ax.annotate('{}'.format(row['2009']), xy=(row['2009'], idx), xytext=(row['2009']+0.5,idx-0.05), xycoords='data', color=c)
ax.annotate('{}'.format(row['2013']), xy=(row['2013'], idx), xytext=(row['2013']-2.5,idx-0.05), xycoords='data', color=c)
ax.set_yticks(np.arange(len(df)))
ax.set_yticklabels(df['Party'])
ax.grid()
ax.set_xlim(-5,45)
ax.tick_params('x', length=0, which='major')
ax.tick_params('y', length=0, which='major')
ax.annotate('2009', xy=(0.25,0.85), xytext=(0.25,0.93), xycoords='figure fraction', arrowprops=dict(arrowstyle='-'))
ax.annotate('2013', xy=(0.45,0.85), xytext=(0.45,0.93), xycoords='figure fraction', arrowprops=dict(arrowstyle='-'))
plt.show()