Angry Bird
Angry Bird

Reputation: 89

How to fix the bar chart in python (custom bar chart)?

I am using the following code to generate the bar chart below

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()

As you can see from the given figure I am facing multiple issues.

  1. Need to set the axis label properly, now only works for y-label.
  2. xticklabels has overlap since the rotation is not working well.

I will really appreciate if anyone can help me to fix it?

enter image description here

Upvotes: 1

Views: 48

Answers (1)

David
David

Reputation: 891

This should work

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')

enter image description here

Upvotes: 3

Related Questions