I have two plots overlaid on each other generated by the following code:
import matplotlib.pyplot as plt
import pandas as pd
width=.5
t=pd.DataFrame({'bars':[3.4,3.1,5.1,5.1,3.8,4.2,5.2,4.0,3.6],'lines':[2.4,2.2,2.4,2.1,2.0,2.1,1.9,1.8,1.9]})
t['bars'].plot(kind='bar',width=width)
t['lines'].plot(secondary_y=True, color='red')
ax=plt.gca()
plt.xlim([-width,len(t['bars'])-width])
ax.set_xticklabels(('1','2','3','4','5','6','7','8','9'))
plt.show()
I want to be able to scale the range of the second y axis to go from 0.0 to 2.5 (instead of 1.8 to 2.4) in steps of .5. How can I define this without changing the bar chart at all?
CodePudding user response:
Pandas returns the axis on which it plots when you call the plot function. Just save that axis and modify the limits using the object oriented approach.
import matplotlib.pyplot as plt
import pandas as pd
width=.5
t=pd.DataFrame({'bars':[3.4,3.1,5.1,5.1,3.8,4.2,5.2,4.0,3.6],'lines':[2.4,2.2,2.4,2.1,2.0,2.1,1.9,1.8,1.9]})
ax1 = t['bars'].plot(kind='bar',width=width)
ax2 = t['lines'].plot(secondary_y=True, color='red')
ax2.set_ylim(0, 2.5)
ax1.set_xlim([-width,len(t['bars'])-width])
ax1.set_xticklabels(('1','2','3','4','5','6','7','8','9'))
plt.show()