【问题标题】:Add grid and change size in barh python在 barh python 中添加网格并更改大小
【发布时间】:2020-09-07 08:26:17
【问题描述】:

我正在使用 matplotlib 绘制水平图。我想添加网格并更改绘图的大小以避免标签重叠。我的代码如下所示:

baseline = [0.5745,0.5282,0.4923,0.5077,0.5487,0.5385,0.5231]
low = [0.2653,0.3878,0.3673,0.5510,0.2245,0.5714,0.3265]
high = [0.5102,0.5102,0.3673,0.3877,0.5306,0.4286,0.49]
index = ['Bagging','Decision tree','Gussian Naive Bayes','Logistic regression','Random forest','SVM','k-NN']
df = pd.DataFrame({'Baseline': baseline,'ttd lower than median': low,'ttd higher than median': high}, index=index)
plt.figure(figsize = (6,12))
ax.yaxis.grid(color='gray', linestyle='dashed')
ax = df.plot.barh()

结果图如下所示:

但是,它没有显示网格,并且“plt.figure(figsize = (6,12))”似乎不起作用。我怎样才能解决这个问题?提前致谢!

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:
    • 使用plt.legend 指定图例的位置
      • 放大图不一定会使图例更合适
    • 使用plt.grid()显示网格
    • plt.figure(figsize = (6,12)) 不起作用,因为数据框图未使用此轴。
    fig, ax = plt.subplots(figsize=(7, 12))
    ax.yaxis.grid(color='gray', linestyle='dashed')
    df.plot.barh(ax=ax)  # ax=ax lets the dataframe plot use the subplot axes
    plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')  # place the legend outside
    plt.grid()  # show the grid
    

    • 或者,使用df.plot.barh(ax=ax, figsize=(7, 12))
    p = df.plot.barh(figsize=(7, 8))
    p.yaxis.grid(color='gray', linestyle='dashed')
    plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      相关资源
      最近更新 更多