Home > Enterprise >  How to scale an axis in matplotlib and avoid axes plotting over each other
How to scale an axis in matplotlib and avoid axes plotting over each other

Time:09-28

I have a dataframe:

Date,a,b,c
01/11/21,10,5,34
02/11/21,11,5.5,32
03/11/21,12,6,311
04/11/21,13,6.5,32
05/11/21,14,7,56
06/11/21,15,7.5,676
07/11/21,16,8,534

When I plot it with the code below (3 axes: a,b and c) - axes a and b identically plot over each other, because they are of the same scale. As below:

enter image description here

How can my code be modified so that each plotted line is obvious?

df = pd.read_csv("plot.csv")

yax1 ='a'
yax2 = 'b'
yax3 = 'c'

ax1 = df.plot(x='Date', y=yax1, color='black', figsize=(12,7), legend=False)
ax1.set_ylabel(yax1)
ax1.yaxis.label.set_color('black')
ax1.set_xlabel('Date')    

plt.subplots_adjust(right=0.85)    

ax2 = ax1.twinx()
ax2.spines['right'].set_position(('axes', 1.0))
df[yax2].plot(ax=ax2, color='green')
ax2.set_ylabel(yax2)
ax2.yaxis.label.set_color('green')
ax2.legend([ax1.get_lines()[0], ax2.get_lines()[0]], [yax1, yax2], loc='upper left')              # loc can be 'best' also
ax2.spines['right'].set_color('green')     

ax3 = ax1.twinx()
ax3.spines['right'].set_position(('axes', 1.1))
df[yax3].plot(ax=ax3, color='red')
ax3.yaxis.label.set_color('red')
ax3.legend([ax1.get_lines()[0], ax2.get_lines()[0], ax3.get_lines()[0]],[yax1, yax2, yax3], loc='upper left')
ax3.spines['right'].set_color('red')                

plt.tight_layout()
plt.show()

CodePudding user response:

You could consider changing the y-axis limits for either ax1 (a) or ax2 (b). As an example, using the piece of code below I scale the y-axis of ax1:

# Get current y-axis limits
ax1_y_old_lower, ax1_y_old_upper = ax1.get_ylim()

# Scale the y-axis limits
scale_factor = 0.1
ax1_y_new_lower = (1 - scale_factor) * ax1_y_old_lower
ax1_y_new_upper = (1   scale_factor) * ax1_y_old_upper

# Set the scaled y-axis limits to be the new limits
ax1.set_ylim(ax1_y_new_lower, ax1_y_new_upper)

As you can see, I first get the current y-axis limits and subsequently scale them using a scaling factor (i.e. scale_factor). Of course, you can change the value of this scaling factor to get the desired result.

For reference, this leads to the following output graph: Graph after scaling ax1

  • Related