0

I want to rotate the xtick labels in this multi-axis plot (the code I use for a single axis plot doesn't work).

enter image description here

What the xtick labels should look like (ignore the different dates) enter image description here

The code

import numpy as np
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1 import host_subplot
from mpl_toolkits import axisartist

# Create the data
data = {
    'Date': pd.date_range('2021-01-1', '2021-01-30'),
    'Close': np.linspace(100, 200, num=30) + np.random.normal(scale=10, size=30),
    'Volume': np.random.randint(500, 2000, size=30)
}
df = pd.DataFrame(data)
df = df.set_index(df.Date)

# Create the axis
plt.figure(figsize=(10,5))
host = host_subplot(111, axes_class=axisartist.Axes)
ax1 = host.twinx()
ax1.axis["right"].toggle(all=True)

# Plot the closing prices
line, = host.plot(df.index, df.Close, label="Close")
host.set_ylabel("Close")
host.yaxis.label.set_color(line.get_color())

# Plot the volumes
bar = ax1.bar(df.index, df.Volume, alpha=0.2, color='red', label="Volume")
ax1.set_ylabel('Volume')
ax1.yaxis.label.set_color('red')

host.legend()
plt.show()

The code is based on this matplotlib example:
https://matplotlib.org/stable/gallery/axisartist/demo_parasite_axes2.html#sphx-glr-gallery-axisartist-demo-parasite-axes2-py

Normal solutions for single-axis plots don't work, eg. Rotate axis text in python matplotlib

Alter
  • 3,110
  • 4
  • 28
  • 52

0 Answers0