Home > Enterprise >  matplotlib pyplot ParasiteAxes not allowing formatting of x label
matplotlib pyplot ParasiteAxes not allowing formatting of x label

Time:11-22

The following can independently set the color, font and font size for the left and right y-axis, but can not set the font or font size for the x-axis. It can set the x-axis color. I'm using ParasiteAxes as they allow me to modify the plot formatting in other ways while working with matplotlib.animation. The goal is to be able to set the font, font size, and color differently for each of the axis labels and those should be independent of the ticklabels (at least the size). `

from mpl_toolkits.axisartist.parasite_axes import HostAxes, ParasiteAxes
import matplotlib.pyplot as plt

plt.rcParams.update({'font.size': 16})
plt.rcParams.update({'font.weight': 'normal'})
plt.rcParams.update({'font.family': 'times new roman'})

x = [0, 1, 2]
y1 = [0, 1, 2]
y2 = [1, 2, 3]

fig = plt.figure(figsize=(8, 4.5))

host = fig.add_axes([0.10, 0.1, 0.60, 0.85], axes_class=HostAxes)
host.set_xlim(0, 2)
host.axis["right"].set_visible(False)
host.axis["left"].set_visible(False)

host.set_xlabel('X Axis', fontsize=24, fontfamily='courier new', color='tab:green')

y1_color = 'tab:red'
y1_axis = ParasiteAxes(host, sharex=host)
host.parasites.append(y1_axis)
y1_axis.axis['y1'] = y1_axis.new_fixed_axis(loc='left', offset=(0, 0))
y1_axis.set_ylim(0, 4)
y1_axis.set_ylabel('Y1 Axis')
y1_axis.axis['y1'].label.set(fontsize=12, color=y1_color, fontfamily='courier new')
y1_line, = y1_axis.plot([], [], lw=2, color=y1_color)
y1_line.set_data(x, y1)

y2_color = 'tab:blue'
y2_axis = ParasiteAxes(host, sharex=host)
host.parasites.append(y2_axis)
y2_axis.axis['y2'] = y2_axis.new_fixed_axis(loc='right', offset=(0, 0))
y2_axis.set_ylim(0, 4)
y2_axis.set_ylabel('y2 Axis')
y2_axis.axis['y2'].label.set(fontsize=24, color=y2_color, fontfamily='arial')
y2_line, = y2_axis.plot([], [], lw=2, color=y2_color)
y2_line.set_data(x, y2)

plt.show()

`

Here's the resulting plot:

pyplot output with undesired x-label font and font size

I was expecting the x-axis label in the code above to be green 24-point Courier New, but in the plot it appears at green 16-point Times New Roman (taken on the rcParams except for the color. If the rcParams are modified then the ticklabels are modified which I want to remain independent of the x-axis label. I would appreciate a solution and also an explanation as to why the two axis objects are behaving differently.

CodePudding user response:

I can't speak to why the way you are currently setting your xlabel properties is not working but it looks like using

host.set_xlabel('X Axis')
host.axis["bottom"].label.set(fontsize=24, fontfamily='courier new', color='tab:green')

instead of host.set_xlabel('X Axis', fontsize=24, fontfamily='courier new', color='tab:green') solves it with matplotlib 3.6.2.

enter image description here

  • Related