【问题标题】:matplotlib bar chart with data frame row names as legendmatplotlib 条形图,数据框行名称作为图例
【发布时间】:2016-05-03 02:47:06
【问题描述】:

我正在尝试使用 pandas 数据框的值来设置条形图的图例。我搜索并找不到解决方案,我使用了另一个来自 SO 的 sn-p 来注释条形图。生成的图以我想要的不同颜色显示系列中的条形图,甚至显示条形图的值。例如,在 Excel 中,您可以有一个将系列值显示为图例的图例。我正在尝试在这里获得该功能。

这是一个 MWE:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import seaborn, itertools
seaborn.set()

def flip(items, ncol):
    return itertools.chain(*[items[i::ncol] for i in range(ncol)])

def annotateBars(row, ax=ax):
    if row['A'] < 0.2:
        color = 'black'
        vertalign = 'bottom'
        vertpad = 0.02
    else:
        color = 'white'
        vertalign = 'top'
        vertpad = -0.02

    ax.text(row.name, row['A'] + vertpad, "{:.4f}%".format(row['A']),
            zorder=10, rotation=90, color=color,
            horizontalalignment='center',
            verticalalignment=vertalign,
            fontsize=14, weight='heavy')

labels1=["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
width = 0.75
my_colors = 'gbkymc'
arr1 = np.random.random((1, 5))
arr1_ind = np.arange((arr1.shape[1]))
df_arr1 = pd.DataFrame(zip(*arr1), index = arr1_ind, columns = ['A'])
ax = df_arr1.plot(kind='bar', width = 0.85, alpha = 0.5, color = my_colors)
# plt.xticks(arr1_ind+width/4, arr1_ind)

ax.set_xticks(arr1_ind)
ax.set_xticklabels([labels1[i] for i in arr1_ind])
hndls, lbls = ax.get_legend_handles_labels()
plt.legend(flip(hndls, 2), flip(labels1, 2), loc='best', ncol=2)

junk = df_arr1.apply(annotateBars, ax=ax, axis=1)
plt.tick_params(
    axis='x',          # changes apply to the x-axis
    which='both',      # both major and minor ticks are affected
    bottom='off',      # ticks along the bottom edge are off
    top='off',         # ticks along the top edge are off
    labelbottom='off') # labels along the bottom edge are off
plt.tight_layout()
plt.show()

【问题讨论】:

    标签: python numpy pandas matplotlib


    【解决方案1】:

    听起来您希望图例中每种颜色都有一个项目。

    现在,您只创建了一个艺术家(一次调用 bar),所以图例只有一个条目。

    作为一个简单的例子来做一些你想做的事情:

    import numpy as np
    import matplotlib.pyplot as plt
    import pandas as pd
    
    df = pd.DataFrame({
            'value':np.random.random(5),
            'label':['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
            'color':['g', 'b', 'k', 'y', 'm']})
    
    fig, ax = plt.subplots()
    
    # Plot each bar separately and give it a label.
    for index, row in df.iterrows():
        ax.bar([index], [row['value']], color=row['color'], label=row['label'],
               alpha=0.5, align='center')
    
    ax.legend(loc='best', frameon=False)
    
    # More reasonable limits for a vertical bar plot...
    ax.margins(0.05)
    ax.set_ylim(bottom=0)
    
    # Styling similar to your example...
    ax.patch.set_facecolor('0.9')
    ax.grid(color='white', linestyle='-')
    ax.set(axisbelow=True, xticklabels=[])
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 2016-11-14
      • 2020-05-06
      • 2017-06-11
      相关资源
      最近更新 更多