【问题标题】:How to fix the bar chart in python (custom bar chart)?如何修复python中的条形图(自定义条形图)?
【发布时间】:2021-04-25 21:31:50
【问题描述】:

我正在使用下面的代码来生成下面的条形图

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

width = .5 
# width of a bar

m1_t = pd.DataFrame({
 'Google' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30],
 'Statistical' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30],
 'Tomtom' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30],
 'Simulation' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30]})

m1_t[['Google','Statistical','Tomtom']].plot(kind='bar', width = width)
m1_t['Simulation'].plot(secondary_y=True)

ax1 = plt.gca()
#plt.xlim([-width, len(m1_t['Statistical'])-width])
labels = ['0:00', '01:00', 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
ax1.set_xticklabels(labels)
plt.setp(ax1.get_xticklabels(), rotation=45);
plt.legend(loc=[0.8, 0.9])
fig.tight_layout()
plt.xlim(0, 24)
plt.ylim(0,100)
ax1.set_xlabel("Time (h)")
ax1.set_ylabel("Number of Buses")
#ax.set_ylabel('Scores')
ax1.set_title('Scores by group')
plt.savefig('foo.png')
plt.show()

从给定的图中可以看出,我面临着多个问题。

  1. 需要正确设置轴标签,现在只适用于y标签。
  2. xticklabels 有重叠,因为旋转效果不好。

如果有人能帮我解决这个问题,我将不胜感激?

【问题讨论】:

    标签: python pandas numpy matplotlib bar-chart


    【解决方案1】:

    这应该可以工作

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    
    width = .5 
    # width of a bar
    
    m1_t = pd.DataFrame({
     'Google' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30],
     'Statistical' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30],
     'Tomtom' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30],
     'Simulation' : [90,40,30,30,30,25,25,20,15,10,90,40,30,30,30,25,25,20,15,10,90,40,30,30]})
    
    
    
    
    fig,ax1=plt.subplots(1,1,figsize=(12,6))
    m1_t[['Google','Statistical','Tomtom']].plot(kind='bar', width = width,ax=ax1,color=['tab:blue','tab:orange','tab:green'])
    m1_t['Simulation'].plot(secondary_y=True,ax=ax1,color='tab:blue')
    #plt.xlim([-width, len(m1_t['Statistical'])-width])
    labels = ['0:00', '01:00', 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
    ax1.set_xticklabels(labels, rotation=90);
    ax1.legend(loc='upper right',labels=['Google','Statistical','Tomtom'])
    ax1.set_xlim(0, 24)
    ax1.set_ylim(0,100)
    ax1.set_xlabel("Time (h)")
    ax1.set_ylabel("Number of Buses")
    ax1.set_title('Scores by group')
    fig.savefig('foo.png')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2022-12-10
      • 2023-01-21
      • 1970-01-01
      • 2013-03-01
      相关资源
      最近更新 更多