How should I align the text labels against the x tickers in the graph here ? I am using host.set_xticklabels(labels,rotation='vertical') , but that doesnt seem to work . My labels are sentences and some could be smaller/larger than others, like "The mummy returns part 2" - How do I pad a space below the x axis to accommodate this ?
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
path='/home/project/df.csv'
df=pd.read_csv(path,sep=',',header='infer')
xs =range(0,101)
ys =list(df['B'].ix[0:100])
zs=list(df['C'].ix[0:100])
ws=list(df['D'].ix[0:100])
if 1:
host = host_subplot(111, axes_class=AA.Axes)
p1, = host.plot(xs, ys, label='B')
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right",
axes=par2,
offset=(offset, 0))
par2.axis["right"].toggle(all=True)
host.set_xlim(min(xs), max(xs))
host.set_ylim(100, max(ys))
host.set_xlabel("A")
host.set_ylabel("B")
par1.set_ylabel("C")
par2.set_ylabel("D")
p2, = par1.plot(xs, ws, label='C',color='red')
p3, = par2.plot(xs, zs, label='D',color='green')
for tl in par1.get_yticklabels():
tl.set_color('red')
for tl in par2.get_yticklabels():
tl.set_color('green')
for tl in par1.get_yticklabels():
tl.set_color('r')
for tl in par2.get_yticklabels():
tl.set_color('g')
host.legend()
host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())
start, end, stepsize=0,len(df)-1,3
host.xaxis.set_ticks(np.arange(start, end, stepsize))
labels=list(df['A'])[0::stepsize]
host.set_xticklabels(labels,rotation='vertical')
plt.tight_layout()
plt.draw()
plt.show()
I need to align the "black" mass as in the picture.
I tried the suggestions in the example here python rotate values on xaxis to not overlap - plt.xticks(x, labels, rotation='vertical') , and more, but that did not work.
Edit -: From Kazemakaze's feedback below, here's what I tried -: f,host= plt.subplots() #host = host_subplot(111, axes_class=AA.Axes) but I must adapt the rest of the code as well . Can you provide an example with twinx axis where this works ?
I am adapting my code to this Secondary axis with twinx(): how to add to legend? and the rotation works now, need some pointers on the secondary axis though.