条形图,每个条带垂直线

时间:2020-02-12 16:49:10

标签: python pandas matplotlib

%matplotlib inline
import matplotlib
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({'index' : ['A', 'B', 'C', 'D'], 'first': [1.2, 1.23, 1.32, 1.08], 'second': [2, 2.2, 3, 1.08], 'max': [1.5, 3, 0.9, 'NaN']}).set_index('index')

我想绘制一个以firstsecond为条形图的水平条形图。 我想使用max列在其他值处显示垂直线。

我现在只管理条形图。

赞:

enter image description here

关于如何实现这一目标的任何提示?

thx

1 个答案:

答案 0 :(得分:2)

我已将NaN替换为一些有限值,然后可以使用以下代码

df = pd.DataFrame({'index' : ['A', 'B', 'C', 'D'], 'first': [1.2, 1.23, 1.32, 1.08], 
                   'second': [2, 2.2, 3, 1.08], 'max': [1.5, 3, 0.9, 2.5]}).set_index('index')

plt.barh(range(4), df['first'], height=-0.25, align='edge')
plt.barh(range(4), df['second'], height=0.25, align='edge', color='red')
plt.yticks(range(4), df.index);

for i, val in enumerate(df['max']):
    plt.vlines(val, i-0.25, i+0.25, color='limegreen')

enter image description here