如何为字典绘制条形图?

时间:2019-10-02 12:29:21

标签: python

我想使用字典使用matplotlib绘制条形图:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
plt.style.use('ggplot')

import numpy as np

dictionary = {0: 0, 1: 13.2, 2: 29.7, 3: 43, 4: 52}
plt.bar(list(dictionary.keys()), dictionary.values(), color='red')
plt.xlabel('X')
plt.ylabel('Y(%)')
plt.show()

enter image description here

但是,我想得到一张这样的照片:

enter image description here

能帮我吗?预先谢谢你。

1 个答案:

答案 0 :(得分:0)

您可以像这样显式绘制黑线:

for k,v in dictionary.items(): 
    plt.plot([0,k],[v,v], color='black')     

此代码仅在两个点之间绘制一条线,每个条形的点分别为(0,Y_n)(x_n, Y_n)。 (n是小节的编号)

结果:

Bar graph with top lines

相关问题