用箭头高亮显示matplotlib条形图上的数据

2024-10-01 00:21:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想指出使用pandas dataframe和matplotlib绘制的条形图上的数据点。如果我在下面的简单示例中使用散点图(用数字数据替换下面数据中的类别,用箭头进行打印和高亮显示效果很好),则如果未调用条件,则会绘制条形图数据,但在运行条件语句时“崩溃”。我想不出是什么问题。我们将不胜感激

import pandas as pd
    import matplotlib.pyplot as plot
    %matplotlib inline
    bar_data = {'A':4,'B':8,'C':7,'D':1,'E':3,'F':9,'G':0,'H':4,'J':2,'K':8}
    bardf = pd.DataFrame(list(bar_data.items()),columns = ['x','y'])
    #display(bardf)
    bar_fig=bardf.plot.bar('x', 'y',figsize=(10,6))
    for index,row in bardf.iterrows():
           if row['y']==0:
                x=row['x']
                y=row['y']
                print(x,y)
                bar_fig.annotate(x,color='magenta', xy=(x, y), xytext=(x, 2),
                    bbox=dict(boxstyle='round,pad=0.3', fc='green', alpha=0.3),arrowprops=dict(arrowstyle='->',color='green'))

Tags: 数据importpandasdataplotmatplotlibasfig
1条回答
网友
1楼 · 发布于 2024-10-01 00:21:31

我不确定这是否解决了您的问题,但是您应该使用它的位置,而不是在您的例子中是字符的x

bar_fig=bardf.plot.bar('x', 'y',figsize=(10,6))
for index,row in bardf.iterrows():
   if row['y']==0:
        x=row['x']
        y=row['y']
        print(index)
        bar_fig.annotate(x,color='magenta', xy=(index, y), 
                         xytext=(index,2),bbox=dict(boxstyle='round,pad=0.3',fc='green', alpha=0.3),arrowprops=dict(arrowstyle='->',color='green'))

相关问题 更多 >