Rotating 2nd y-axis tick labels in matplotlib - python

I need to rotate the 2nd y-axis ticklabel and add a label for this axis as well in the figure below
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms
fig, ax1 = plt.subplots(constrained_layout=True)
x = [61,62,62,59,62,59,62,63,61,60,103,104,109,105,109,105,109,111,110,107]
y = [62,62,62,62,60,60,62,62,62,63,106,107,106,106,105,105,105,106,107,108]
ax1.plot(x,y,'b.')
x2 = [2.2,3.4,4.3,5.1,5.5,5.7]
y2 = [2.3,2.8,3.2,3.9,4.5,5.9]
ax2 = ax1.twinx().twiny()
ax2.tick_params(axis="y",labelrotation=90,direction='out',length=6, width=2, colors='r',grid_color='r', grid_alpha=0.5) #called tick_params before the plot and didn't work
ax2.plot(x2,y2,'r.')
ax2.set_xlim(0,10)
ax2.set_ylim(0,10)
ax2.set_yticklabels(['Label1', 'Label2', 'Label3'], rotation=90) #y ticklabels is not rotating
ax2.set_xlabel('abc', rotation=0, fontsize=20, labelpad=20)
ax2.set_ylabel('abc', rotation=0, fontsize=20, labelpad=20) #y label is not wroking
plt.yticks(rotation=90)
line = mlines.Line2D([0, 1], [0, 1], color='red')
transform = ax2.transAxes
line.set_transform(transform)
ax2.add_line(line)
plt.show()
This code produced the figure below
The problem is ax2.set_yticklabels and ax2.set_ylabel don't work.
I want to add a label to 2nd y-axis and rotate the tick label for that axis. Also, how to control the position of the tick mark at these axes, I want it to be at the same position of tick marks of 1st y-axis and 1st x-axis. So Label1 will shift up and 0 will shift right
Thanks

When you are instancing ax2 = ax1.twinx().twiny(), you can no longer modify the y axis. Instead, create two axes and modify accordingly. Modified code and the result is below.
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms
fig, ax1 = plt.subplots(constrained_layout=True)
x = [61,62,62,59,62,59,62,63,61,60,103,104,109,105,109,105,109,111,110,107]
y = [62,62,62,62,60,60,62,62,62,63,106,107,106,106,105,105,105,106,107,108]
ax1.plot(x,y,'b.')
x2 = [2.2,3.4,4.3,5.1,5.5,5.7]
y2 = [2.3,2.8,3.2,3.9,4.5,5.9]
ax2 = ax1.twinx() # ax2 handles y
ax3 = ax2.twiny() # ax3 handles x
ax3.plot(x2,y2,'r.')
ax3.set_xlim(0,10)
ax2.set_ylim(0,10)
ax3.set_xlabel('abc', rotation=0, fontsize=20, labelpad=20)
ax2.set_ylabel('abc', rotation=0, fontsize=20, labelpad=20)
ax2.tick_params(axis="y",labelrotation=90,direction='out',length=6, width=2, colors='r',grid_color='r', grid_alpha=0.5)
ax2.set_yticklabels(['Label1', 'Label2', 'Label3'], rotation=-90)
plt.yticks(rotation=90)
line = mlines.Line2D([0, 1], [0, 1], color='red')
transform = ax2.transAxes
line.set_transform(transform)
ax2.add_line(line)
plt.show()
The resulting graph has all the y label/tick modifications.

Related

Multiple label positions for same axis in Matplotlib

I have a long bar chart with lots of bars and I wanna improve its reability from axis to the bars.
Suppose I have the following graph:
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
y = np.linspace(1,-1,20)
x = np.arange(0,20)
labels = [f'Test {i}' for i in x]
fig, ax = plt.subplots(figsize=(12,8))
sns.barplot(y = y, x = x, ax=ax )
ax.set_xticklabels(labels, rotation=90)
which provides me the following:
All I know is how to change the label position globally across the chart. How can I change the axis layout to be cantered in the middle and change its label position based on a condition (in this case, being higher or lower than 0)? What I want to achieve is:
Thanks in advance =)
You could remove the existing x-ticks and place texts manually:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
y = np.linspace(1,-1,20)
x = np.arange(0,20)
labels = [f'Test {i}' for i in x]
fig, ax = plt.subplots(figsize=(12,8))
sns.barplot(y = y, x = x, ax=ax )
ax.set_xticks([]) # remove existing ticks
for i, (label, height) in enumerate(zip(labels, y)):
ax.text(i, 0, ' '+ label+' ', rotation=90, ha='center', va='top' if height>0 else 'bottom' )
ax.axhline(0, color='black') # draw a new x-axis
for spine in ['top', 'right', 'bottom']:
ax.spines[spine].set_visible(False) # optionally hide spines
plt.show()
Here is another approach, I'm not sure whether it is "more pythonic".
move the existing xaxis to y=0
set the tick marks in both directions
put the ticks behind the bars
prepend some spaces to the labels to move them away from the axis
realign the tick labels depending on the bar value
fig, ax = plt.subplots(figsize=(12, 8))
sns.barplot(y=y, x=x, ax=ax)
ax.spines['bottom'].set_position('zero')
for spine in ['top', 'right']:
ax.spines[spine].set_visible(False)
ax.set_xticklabels([' ' + label for label in labels], rotation=90)
for tick, height in zip(ax.get_xticklabels(), y):
tick.set_va('top' if height > 0 else 'bottom')
ax.tick_params(axis='x', direction='inout')
ax.set_axisbelow(True) # ticks behind the bars
plt.show()

How to add axis label (x and y) and rotate y axis numbers with Matplotlib

How to add axis label (x and y) and rotate y axis numbers with Matplotlib like on the image below ?
I tried plt.yticks(rotation=45) to rotate the y axis numbers but it's not taken into account.
Besides, I'm also trying to have one 0 instead of two in my example code and a square grid instead of rectangles.
from mpl_toolkits.axisartist.axislines import SubplotZero
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)
for direction in ["xzero", "yzero"]:
# adds arrows at the ends of each axis
ax.axis[direction].set_axisline_style('->')
# adds X and Y-axis from the origin
ax.axis[direction].set_visible(True)
ax.axis['yzero'].set_ticklabel_direction("-")
for direction in ["left", "right", "bottom", "top"]:
# hides borders
ax.axis[direction].set_visible(False)
x = np.linspace(-5, 5, 100)
ax.plot(x, -x**2+16, color="#ab74a6", linewidth=3)
plt.title(r'$y = -x^2+16$')
plt.yticks(rotation=45)
plt.axis([-5, 5, -10, 20])
plt.grid(True)
plt.show()
Here's a working code example using spines rather than SubplotZero:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)
x = np.linspace(-5, 5, 100)
ax.plot(x, -x**2+16, color="#ab74a6", linewidth=3)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# hide one of the zero labels and adjust the other
ax.yaxis.get_major_ticks()[3].label1.set_visible(False)
ax.xaxis.get_major_ticks()[3].label1.set_horizontalalignment("right")
ax.plot(1, 0, ">k", transform=ax.get_yaxis_transform(), clip_on=False)
ax.plot(0, 1, "^k", transform=ax.get_xaxis_transform(), clip_on=False)
ax.axis('equal')
ax.set_xlabel('x', position=(1,0), ha='right')
ax.set_ylabel('y', position=(0,1), ha='right', rotation=0)
plt.title(r'$y = -x^2+16$', y=1.08)
plt.grid(True)
plt.show()

Problems rotating xtick labels when using twinx

I have problems with the rotation of my X-axis, I have tried to do the rotation the output plot without errors, but I do not have the results.
# Import Data
#df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")
x = total_test["Dia"].values[:]; y1 = total_test["Confirmados"].values[:]; y2 = total_test["Fallecidos"].values[:]
# Plot Line1 (Left Y Axis)
fig, ax1 = plt.subplots(1,1,figsize=(10,8), dpi= 200)
ax1.plot(x, y1,'g^', color='tab:red')
# Plot Line2 (Right Y Axis)
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax2.plot(x, y2,'bs', color='tab:blue')
# Just Decorations!! -------------------
# ax1 (left y axis)
ax1.set_xlabel('Dias', fontsize=10)
ax1.set_ylabel('Personas Confirmadas', color='tab:red', fontsize=20)
ax1.tick_params(axis='y', rotation=0, labelcolor='tab:red' )
# ax2 (right Y axis)
ax2.set_ylabel("Personas Fallecidas", color='tab:blue', fontsize=20)
ax2.tick_params(axis='y', rotation=0, labelcolor='tab:blue')
ax2.set_title("Personas Confirmadas y Fallecidas por Covid-19 Peru", fontsize=15)
#ax2.set_xticks(x)
ax2.set_xticklabels(x[::],fontsize=10,rotation=90)
plt.show()
Any commands for the xaxis need to occur before ax2.
Verify date is in a datetime format and set as the index.
import pandas as pd
import matplotlib.pyplot as plt
# read data
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv")
# verify the date column is a datetime format and set as index
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)
#plot
# create figure
fig, ax1 = plt.subplots(1, 1, figsize=(10,8))
# 1st plot
ax1.plot(df['pop'], color='tab:red')
# set xticks rotation before creating ax2
plt.xticks(rotation=90)
# 2nd plot (Right Y Axis)
ax2 = ax1.twinx() # create the 'twin' axis on the right
ax2.plot(df['unemploy'], color='tab:blue')
plt.show()
Plot directly with pandas.DataFrame.plot
# load data
df = pd.read_csv("https://github.com/selva86/datasets/raw/master/economics.csv", parse_dates=True, index_col=[0])
# plot and rotate the tick labels with rot= in the first plot call
ax = df.plot(y='pop', color='tab:red', figsize=(10,8), rot=90)
ax2 = ax.twinx()
df.plot(y='unemploy', color='tab:blue', ax=ax2)
ax2.legend(loc='upper right')

Merge matplotlib subplots with shared x-axis

I have two graphs to where both have the same x-axis, but with different y-axis scalings.
The plot with regular axes is the data with a trend line depicting a decay while the y semi-log scaling depicts the accuracy of the fit.
fig1 = plt.figure(figsize=(15,6))
ax1 = fig1.add_subplot(111)
# Plot of the decay model
ax1.plot(FreqTime1,DecayCount1, '.', color='mediumaquamarine')
# Plot of the optimized fit
ax1.plot(x1, y1M, '-k', label='Fitting Function: $f(t) = %.3f e^{%.3f\t} \
%+.3f$' % (aR1,kR1,bR1))
ax1.set_xlabel('Time (sec)')
ax1.set_ylabel('Count')
ax1.set_title('Run 1 of Cesium-137 Decay')
# Allows me to change scales
# ax1.set_yscale('log')
ax1.legend(bbox_to_anchor=(1.0, 1.0), prop={'size':15}, fancybox=True, shadow=True)
Now, i'm trying to figure out to implement both close together like the examples supplied by this link
http://matplotlib.org/examples/pylab_examples/subplots_demo.html
In particular, this one
When looking at the code for the example, i'm a bit confused on how to implant 3 things:
1) Scaling the axes differently
2) Keeping the figure size the same for the exponential decay graph but having a the line graph have a smaller y size and same x size.
For example:
3) Keeping the label of the function to appear in just only the decay graph.
Any help would be most appreciated.
Look at the code and comments in it:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import gridspec
# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig = plt.figure()
# set height ratios for subplots
gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
# the first subplot
ax0 = plt.subplot(gs[0])
# log scale for axis Y of the first subplot
ax0.set_yscale("log")
line0, = ax0.plot(x, y, color='r')
# the second subplot
# shared axis X
ax1 = plt.subplot(gs[1], sharex = ax0)
line1, = ax1.plot(x, y, color='b', linestyle='--')
plt.setp(ax0.get_xticklabels(), visible=False)
# remove last tick label for the second subplot
yticks = ax1.yaxis.get_major_ticks()
yticks[-1].label1.set_visible(False)
# put legend on first subplot
ax0.legend((line0, line1), ('red line', 'blue line'), loc='lower left')
# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)
plt.show()
Here is my solution:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig, (ax1,ax2) = plt.subplots(nrows=2, sharex=True, subplot_kw=dict(frameon=False)) # frameon=False removes frames
plt.subplots_adjust(hspace=.0)
ax1.grid()
ax2.grid()
ax1.plot(x, y, color='r')
ax2.plot(x, y, color='b', linestyle='--')
One more option is seaborn.FacetGrid but this requires Seaborn and Pandas libraries.
Here are some adaptions to show how the code could work to add a combined legend when plotting a pandas dataframe. ax=ax0 can be used to plot on a given ax and ax0.get_legend_handles_labels() gets the information for the legend.
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
dates = pd.date_range('20210101', periods=100, freq='D')
df0 = pd.DataFrame({'x': np.random.normal(0.1, 1, 100).cumsum(),
'y': np.random.normal(0.3, 1, 100).cumsum()}, index=dates)
df1 = pd.DataFrame({'z': np.random.normal(0.2, 1, 100).cumsum()}, index=dates)
fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True, gridspec_kw={'height_ratios': [2, 1], 'hspace': 0})
df0.plot(ax=ax0, color=['dodgerblue', 'crimson'], legend=False)
df1.plot(ax=ax1, color='limegreen', legend=False)
# put legend on first subplot
handles0, labels0 = ax0.get_legend_handles_labels()
handles1, labels1 = ax1.get_legend_handles_labels()
ax0.legend(handles=handles0 + handles1, labels=labels0 + labels1)
# remove last tick label for the second subplot
yticks = ax1.get_yticklabels()
yticks[-1].set_visible(False)
plt.tight_layout()
plt.show()

How to plot contourf colorbar in different subplot - matplotlib

This is a very similar question to "How to plot pcolor colorbar in a different subplot - matplotlib". I am trying to plot a filled contour plot and a line plot with a shared axis and the colorbar in a separate subplot (i.e. so it doesn't take up space for the contourf axis and thus muck up the x-axis sharing). However, the x-axis in my code does not rescale nicely:
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
z = np.random.rand(20, 20)
x, y = np.arange(20), np.arange(20)
y2 = np.random.rand(20)
fig = plt.figure(figsize=(8, 8))
gs = mpl.gridspec.GridSpec(2, 2, height_ratios=[1, 2], width_ratios=[2, 1])
ax1 = fig.add_subplot(gs[1, 0])
ax2 = fig.add_subplot(gs[0, 0], sharex=ax1)
ax3 = fig.add_subplot(gs[1, 1])
cont = ax1.contourf(x, y, z, 20)
plt.tick_params(which='both', top=False, right=False)
ax2.plot(x, y2, color='g')
plt.tick_params(which='both', top=False, right=False)
cbar = plt.colorbar(cont, cax=ax3)
cbar.set_label('Intensity', rotation=270, labelpad=20)
plt.tight_layout()
plt.show()
which produces an x-axis scaled from 0 to 20 (inclusive) rather than 0 to 19, which means there is unsightly whitespace in the filled contour plot. Commenting out the sharex=ax1 in the above code means that the x-axis for the contour plot is scaled nicely, but not for the line plot above it and the plt.tick_params code has no effect on either axis.
Is there a way of solving this?
You could also turn off the autoscaling of x-axis for all subsequent call of plot on this axis so that it keeps the range set by contourf and sharex=True :
ax2.set_autoscalex_on(False)
This comes even before your call to ax2.plot() and I think it is better than calling ax2.set_xlim(0, 19) since you do not need to know what are the actual limit of your x-axis that may be needed.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
z = np.random.rand(20, 20)
x, y = np.arange(20), np.arange(20)
y2 = np.random.rand(20)
fig = plt.figure(figsize=(8, 8))
gs = mpl.gridspec.GridSpec(2, 1, height_ratios=[1, 2], width_ratios=[2])
ax1 = fig.add_subplot(gs[1, 0])
ax2 = fig.add_subplot(gs[0, 0], sharex=ax1)
cont = ax1.contourf(x, y, z, 20)
plt.tick_params(which='both', top=False, right=False)
ax2.set_autoscalex_on(False)
ax2.plot(x, y2, color='g')
axins = inset_axes(ax1,
width="5%", # width = 10% of parent_bbox width
height="100%", # height : 50%
loc=6,
bbox_to_anchor=(1.05, 0., 1, 1),
bbox_transform=ax1.transAxes,
borderpad=0,
)
cbar = plt.colorbar(cont, cax=axins)
plt.show()
You can use inset_axes for this without added another axis.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
z = np.random.rand(20, 20)
x, y = np.arange(20), np.arange(20)
y2 = np.random.rand(20)
fig = plt.figure(figsize=(8, 8))
gs = mpl.gridspec.GridSpec(2, 2, height_ratios=[1, 2], width_ratios=[2, 1])
ax1 = fig.add_subplot(gs[1, 0])
ax2 = fig.add_subplot(gs[0, 0], sharex=ax1)
cont = ax1.contourf(x, y, z, 20)
plt.tick_params(which='both', top=False, right=False)
ax2.plot(x, y2, color='g')
plt.tick_params(which='both', top=False, right=False)
axins = inset_axes(ax1,
width="5%", # width = 10% of parent_bbox width
height="100%", # height : 50%
loc=6,
bbox_to_anchor=(1.05, 0., 1, 1),
bbox_transform=ax1.transAxes,
borderpad=0,
)
cbar = plt.colorbar(cont, cax=axins)
plt.savefig('figure.jpg',bbox_inches='tight',dpi=200)

Categories