Seaborn and matplotlib control legend in subplots - python

I have been playing a bit with plt.legend() and ax.legend() and legend from seaborn itself and I think I'm missing something.
My first question is, could someone please explain to me how those go together, how they work and if I have subplots, what is superior to what? Meaning can I set a general definition (eg. have this legend in all subplots in this loc) and then overwrite this definition for specific subplots (eg by ax.legend())?
My second question is practical and showing my problems. Let's take the seaborn Smokers data set to illustrate it on:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# define sizes for labels, ticks, text, ...
# as defined here https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot
SMALL_SIZE = 10
MEDIUM_SIZE = 14
BIGGER_SIZE = 18
plt.rc('font', size=SMALL_SIZE) # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE) # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE) # fontsize of the x and y labels
plt.rc('xtick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('ytick', labelsize=MEDIUM_SIZE) # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE) # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE) # fontsize of the figure title
# create figure
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(16,12))
ylim = (0,1)
sns.boxplot(x= 'day', y= 'tip', hue="sex",
data=tips, palette="Set2", ax=ax1)
sns.swarmplot(x= 'day', y= 'tip', hue="sex",
data=tips, palette="Set2", ax=ax2)
ax2.legend(loc='upper right')
sns.boxplot(x= 'day', y= 'total_bill', hue="sex",
data=tips, palette="Set2", ax=ax3)
sns.swarmplot(x= 'day', y= 'total_bill', hue="sex",
data=tips, palette="Set2", ax=ax4)
plt.suptitle('Smokers')
plt.legend(loc='upper right')
plt.savefig('test.png', dpi = 150)
If I use simply seaborn, I get a legend as in Subplot 1 and 3 -- it has the 'hue' label and follows defined font size. However, I'm not able to control its location (it has some default, see the difference between 1 and 3). If I use ax.legend() as in Subplot 2, then I can modify specific subplot but I lose the seaborn 'hue' feature (notice that the "sex" disappears) and it does not follow my font definitions. If I use plt.legend(), it only affects the Subplot before it (Subplot 4 in this case).
How can I unite all this? Eg. to have one definition for all subplots or how to control the seaborn default? To make clear goal, how to have a legend as in Subplot 1 where the labels come automatically from the data (but I can change them) and the location, font size, ... is set the same for all the subplots (eg. upper right, font size of 10, ...)?
Thank you for help and explanation.

Seaborn legends are always called with the keyword loc=best. This is hardcoded in the sourcecode. You could change the sourcecode, e.g. in this line and replace by ax.legend(). Then setting the rc parameter in your code like
plt.rc('legend', loc="upper right")
would give the desired output.
The only other option is to create the legend manually, like you do in the second case,
ax2.legend(loc="upper right", title="sex", title_fontsize="x-large")

Related

Twinx makes labels disappear

I have an issue with setting the x labels while using twinx function. My original data is a pandas dataframe, namely, df, which has 3 attributes, "name"=product name, "sold"=number of items sold, and "revenue". the name is a pandas series (like "2 shampoo"), but I can't set it to be x tick label (see pic below). How could I set the x labels to display the product's names?
fig = plt.figure() # Create matplotlib figure
ax = fig.add_subplot(111) # Create matplotlib axes
ax2 = ax.twinx() # Create another axes that shares the same x-axis as ax.
width = 0.4
df.sold.plot(kind='bar', color='red', ax=ax, width=width, position=1, rot=90)
df.revenue.plot(kind='bar', color='blue', ax=ax2, width=width, position=0, rot=90)
# print(type(df['name']), "\n", df['name'])
ax.set_ylabel('Sold')
ax2.set_ylabel('Revenue')
ax.legend(['Sold'], loc='upper left')
ax2.legend(['Revenue'], loc='upper right')
plt.show()
You will need to set the labels for X-axis using the set_xticklabels() to show the fields. Add this line after plotting the graph.
ax.set_xticklabels(df.Name)
and you will get the below plot.

How can I draw the right and top axis and remove the left and bottom axis in a Pairplot of Seaborn?

Instead of the default "boxed" axis (and ticks, labels...) style I want to have only the right and top axis, i.e.:
This should be easy, but I can't find the necessary options in the docs.
import seaborn as sns
penguins = sns.load_dataset("penguins")
g=sns.pairplot(penguins)
plt.show()
This is actually not an easy task since you need to take care of a lot of things that are hard-coded by seaborn (spines, ticks, labels).
sns.set_style('ticks')
penguins = sns.load_dataset("penguins")
g=sns.pairplot(penguins)
for ax in g.axes.flat:
sns.despine(left=True, right=False, bottom=True, top=False, ax=ax)
ax.xaxis.set_ticks_position('top')
ax.yaxis.set_ticks_position('right')
plt.setp(ax.yaxis.get_ticklabels(), visible=ax.is_last_col())
plt.setp(ax.xaxis.get_ticklabels(), visible=ax.is_first_row())
for ax1,ax2 in g.axes[:,[0,-1]]:
ax2.yaxis.set_label_position('right')
ax2.set_ylabel(ax1.get_ylabel(), visible=True)
ax1.set_ylabel('')
for ax1,ax2 in g.axes[[0,-1],:].T:
ax1.xaxis.set_label_position('top')
ax1.set_xlabel(ax2.get_xlabel(), visible=True)
ax2.set_xlabel('')
plt.show()

Matplotlib How to change x and y ticks background color? [duplicate]

I'd like to Change the color of the axis, as well as ticks and value-labels for a plot I did using matplotlib and PyQt.
Any ideas?
As a quick example (using a slightly cleaner method than the potentially duplicate question):
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')
plt.show()
Alternatively
[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]
If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.
This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.
import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
# Temporary rc parameters in effect
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.plot(range(10))
ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))
You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:
# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]
For those using pandas.DataFrame.plot(), matplotlib.axes.Axes is returned when creating a plot from a dataframe. Therefore, the dataframe plot can be assigned to a variable, ax, which enables the usage of the associated formatting methods.
The default plotting backend for pandas, is matplotlib.
See matplotlib.spines
Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1, seaborn 0.11.2
import pandas as pd
# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)
# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['right'].set_linewidth(3)
ax.spines['left'].set_color('orange')
ax.spines['left'].set_lw(3)
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
seaborn axes-level plot
import seaborn as sns
# plot the dataframe and assign the returned axes
fig, ax = plt.subplots(figsize=(12, 5))
g = sns.lineplot(data=df, x='date', y='a', color='g', label='a', ax=ax)
# set the margines to 0
ax.margins(x=0, y=0)
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['right'].set_linewidth(3)
ax.spines['left'].set_color('orange')
ax.spines['left'].set_lw(3)
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
seaborn figure-level plot
# plot the dataframe and assign the returned axes
g = sns.relplot(kind='line', data=df, x='date', y='a', color='g', aspect=2)
# iterate through each axes
for ax in g.axes.flat:
# set the margins to 0
ax.margins(x=0, y=0)
# make the top and right spines visible
ax.spines[['top', 'right']].set_visible(True)
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['right'].set_linewidth(3)
ax.spines['left'].set_color('orange')
ax.spines['left'].set_lw(3)
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
motivated by previous contributors, this is an example of three axes.
import matplotlib.pyplot as plt
x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]
x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]
x_values3=[150,200,250,300,350]
y_values3=[-10,-20,-30,-40,-50]
fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)
ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1")
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.tick_params(axis='y', colors="C1")
ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position('right')
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')
plt.show()
You can also use this to draw multiple plots in same figure and style them using same color palette.
An example is given below
fig = plt.figure()
# Plot ROC curves
plotfigure(lambda: plt.plot(fpr1, tpr1, linestyle='--',color='orange', label='Logistic Regression'), fig)
plotfigure(lambda: plt.plot(fpr2, tpr2, linestyle='--',color='green', label='KNN'), fig)
plotfigure(lambda: plt.plot(p_fpr, p_tpr, linestyle='-', color='blue'), fig)
# Title
plt.title('ROC curve')
# X label
plt.xlabel('False Positive Rate')
# Y label
plt.ylabel('True Positive rate')
plt.legend(loc='best',labelcolor='white')
plt.savefig('ROC',dpi=300)
plt.show();
Output:
Here is a utility function that takes a plotting function with necessary args and plots the figure with required background-color styles. You can add more arguments as necessary.
def plotfigure(plot_fn, fig, background_col = 'xkcd:black', face_col = (0.06,0.06,0.06)):
"""
Plot Figure using plt plot functions.
Customize different background and face-colors of the plot.
Parameters:
plot_fn (func): The plot functions with necessary arguments as a lamdda function.
fig : The Figure object by plt.figure()
background_col: The background color of the plot. Supports matlplotlib colors
face_col: The face color of the plot. Supports matlplotlib colors
Returns:
void
"""
fig.patch.set_facecolor(background_col)
plot_fn()
ax = plt.gca()
ax.set_facecolor(face_col)
ax.spines['bottom'].set_color('white')
ax.spines['top'].set_color('white')
ax.spines['left'].set_color('white')
ax.spines['right'].set_color('white')
ax.xaxis.label.set_color('white')
ax.yaxis.label.set_color('white')
ax.grid(alpha=0.1)
ax.title.set_color('white')
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
A use case is defined below
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=50, n_classes=2, n_features=5, random_state=27)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=27)
fig=plt.figure()
plotfigure(lambda: plt.scatter(range(0,len(y)), y, marker=".",c="orange"), fig)

How to edit properties of whiskers, fliers, caps, etc. in Seaborn boxplot

I have created a nested boxplot with an overlayed stripplot using the Seaborn package. I have seen answers on stackoverflow regarding how to edit box properties both for individual boxes and for all boxes using ax.artists generated by sns.boxplot.
Is there any way to edit whisker, cap, flier, etc. properties using a similar method? Currently I have to manually edit values in the restyle_boxplot method of the _BoxPlotter() class in the seaborn -> categorical.py file to get from the default plot to the desired plot:
Default Plot:
Desired Plot:
Here is my code for reference:
sns.set_style('whitegrid')
fig1, ax1 = plt.subplots()
ax1 = sns.boxplot(x="Facility", y="% Savings", hue="Analysis",
data=totalSavings)
plt.setp(ax1.artists,fill=False) # <--- Current Artist functionality
ax1 = sns.stripplot(x="Facility", y="% Savings", hue="Analysis",
data=totalSavings, jitter=.05,edgecolor = 'gray',
split=True,linewidth = 0, size = 6,alpha = .6)
ax1.tick_params(axis='both', labelsize=13)
ax1.set_xticklabels(['Test 1','Test 2','Test 3','Test 4','Test 5'], rotation=90)
ax1.set_xlabel('')
ax1.set_ylabel('Percent Savings (%)', fontsize = 14)
handles, labels = ax1.get_legend_handles_labels()
legend1 = plt.legend(handles[0:3], ['A','B','C'],bbox_to_anchor=(1.05, 1),
loc=2, borderaxespad=0.)
plt.setp(plt.gca().get_legend().get_texts(), fontsize='12')
fig1.set_size_inches(10,7)
EDIT: Note that this method appears to no longer work for matplotlib versions >=3.5. See the answer by #JohanC for an up to date answer
You need to edit the Line2D objects, which are stored in ax.lines.
Heres a script to create a boxplot (based on the example here), and then edit the lines and artists to the style in your question (i.e. no fill, all the lines and markers the same colours, etc.)
You can also fix the rectangle patches in the legend, but you need to use ax.get_legend().get_patches() for that.
I've also plotted the original boxplot on a second Axes, as a reference.
import matplotlib.pyplot as plt
import seaborn as sns
fig,(ax1,ax2) = plt.subplots(2)
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", ax=ax1)
sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", ax=ax2)
for i,artist in enumerate(ax2.artists):
# Set the linecolor on the artist to the facecolor, and set the facecolor to None
col = artist.get_facecolor()
artist.set_edgecolor(col)
artist.set_facecolor('None')
# Each box has 6 associated Line2D objects (to make the whiskers, fliers, etc.)
# Loop over them here, and use the same colour as above
for j in range(i*6,i*6+6):
line = ax2.lines[j]
line.set_color(col)
line.set_mfc(col)
line.set_mec(col)
# Also fix the legend
for legpatch in ax2.get_legend().get_patches():
col = legpatch.get_facecolor()
legpatch.set_edgecolor(col)
legpatch.set_facecolor('None')
plt.show()
For matplotlib 3.5 the rectangles for the boxes aren't stored anymore in ax2.artists, but in ax2.patches. As the background of the subplot is also stored as a rectangular patch, the list of patches needs to be filtered.
The code below further makes a few adjustments:
the exact number of lines belonging to one boxplot is counted, as depending on the boxplot options there can be a different number of lines
saturation=1 is used; seaborn prefers to add some desaturation to larger areas, but lines will be better visible with full saturation
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(12, 5))
sns.set_style("whitegrid")
tips = sns.load_dataset("tips")
sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", ax=ax1)
sns.boxplot(x="day", y="total_bill", hue="smoker", data=tips, palette="Set1", saturation=1, ax=ax2)
box_patches = [patch for patch in ax2.patches if type(patch) == matplotlib.patches.PathPatch]
if len(box_patches) == 0: # in matplotlib older than 3.5, the boxes are stored in ax2.artists
box_patches = ax2.artists
num_patches = len(box_patches)
lines_per_boxplot = len(ax2.lines) // num_patches
for i, patch in enumerate(box_patches):
# Set the linecolor on the patch to the facecolor, and set the facecolor to None
col = patch.get_facecolor()
patch.set_edgecolor(col)
patch.set_facecolor('None')
# Each box has associated Line2D objects (to make the whiskers, fliers, etc.)
# Loop over them here, and use the same color as above
for line in ax2.lines[i * lines_per_boxplot: (i + 1) * lines_per_boxplot]:
line.set_color(col)
line.set_mfc(col) # facecolor of fliers
line.set_mec(col) # edgecolor of fliers
# Also fix the legend
for legpatch in ax2.legend_.get_patches():
col = legpatch.get_facecolor()
legpatch.set_edgecolor(col)
legpatch.set_facecolor('None')
sns.despine(left=True)
plt.show()

How to change the color of the axis, ticks and labels for a plot

I'd like to Change the color of the axis, as well as ticks and value-labels for a plot I did using matplotlib and PyQt.
Any ideas?
As a quick example (using a slightly cleaner method than the potentially duplicate question):
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.spines['bottom'].set_color('red')
ax.spines['top'].set_color('red')
ax.xaxis.label.set_color('red')
ax.tick_params(axis='x', colors='red')
plt.show()
Alternatively
[t.set_color('red') for t in ax.xaxis.get_ticklines()]
[t.set_color('red') for t in ax.xaxis.get_ticklabels()]
If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.
This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.
import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
# Temporary rc parameters in effect
fig, (ax1, ax2) = plt.subplots(1,2)
ax1.plot(range(10))
ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))
You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:
# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]
For those using pandas.DataFrame.plot(), matplotlib.axes.Axes is returned when creating a plot from a dataframe. Therefore, the dataframe plot can be assigned to a variable, ax, which enables the usage of the associated formatting methods.
The default plotting backend for pandas, is matplotlib.
See matplotlib.spines
Tested in python 3.10, pandas 1.4.2, matplotlib 3.5.1, seaborn 0.11.2
import pandas as pd
# test dataframe
data = {'a': range(20), 'date': pd.bdate_range('2021-01-09', freq='D', periods=20)}
df = pd.DataFrame(data)
# plot the dataframe and assign the returned axes
ax = df.plot(x='date', color='green', ylabel='values', xlabel='date', figsize=(8, 6))
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['right'].set_linewidth(3)
ax.spines['left'].set_color('orange')
ax.spines['left'].set_lw(3)
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
seaborn axes-level plot
import seaborn as sns
# plot the dataframe and assign the returned axes
fig, ax = plt.subplots(figsize=(12, 5))
g = sns.lineplot(data=df, x='date', y='a', color='g', label='a', ax=ax)
# set the margines to 0
ax.margins(x=0, y=0)
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['right'].set_linewidth(3)
ax.spines['left'].set_color('orange')
ax.spines['left'].set_lw(3)
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
seaborn figure-level plot
# plot the dataframe and assign the returned axes
g = sns.relplot(kind='line', data=df, x='date', y='a', color='g', aspect=2)
# iterate through each axes
for ax in g.axes.flat:
# set the margins to 0
ax.margins(x=0, y=0)
# make the top and right spines visible
ax.spines[['top', 'right']].set_visible(True)
# set various colors
ax.spines['bottom'].set_color('blue')
ax.spines['top'].set_color('red')
ax.spines['right'].set_color('magenta')
ax.spines['right'].set_linewidth(3)
ax.spines['left'].set_color('orange')
ax.spines['left'].set_lw(3)
ax.xaxis.label.set_color('purple')
ax.yaxis.label.set_color('silver')
ax.tick_params(colors='red', which='both') # 'both' refers to minor and major axes
motivated by previous contributors, this is an example of three axes.
import matplotlib.pyplot as plt
x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]
x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]
x_values3=[150,200,250,300,350]
y_values3=[-10,-20,-30,-40,-50]
fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)
ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")
ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1")
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right')
ax2.tick_params(axis='y', colors="C1")
ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position('right')
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')
plt.show()
You can also use this to draw multiple plots in same figure and style them using same color palette.
An example is given below
fig = plt.figure()
# Plot ROC curves
plotfigure(lambda: plt.plot(fpr1, tpr1, linestyle='--',color='orange', label='Logistic Regression'), fig)
plotfigure(lambda: plt.plot(fpr2, tpr2, linestyle='--',color='green', label='KNN'), fig)
plotfigure(lambda: plt.plot(p_fpr, p_tpr, linestyle='-', color='blue'), fig)
# Title
plt.title('ROC curve')
# X label
plt.xlabel('False Positive Rate')
# Y label
plt.ylabel('True Positive rate')
plt.legend(loc='best',labelcolor='white')
plt.savefig('ROC',dpi=300)
plt.show();
Output:
Here is a utility function that takes a plotting function with necessary args and plots the figure with required background-color styles. You can add more arguments as necessary.
def plotfigure(plot_fn, fig, background_col = 'xkcd:black', face_col = (0.06,0.06,0.06)):
"""
Plot Figure using plt plot functions.
Customize different background and face-colors of the plot.
Parameters:
plot_fn (func): The plot functions with necessary arguments as a lamdda function.
fig : The Figure object by plt.figure()
background_col: The background color of the plot. Supports matlplotlib colors
face_col: The face color of the plot. Supports matlplotlib colors
Returns:
void
"""
fig.patch.set_facecolor(background_col)
plot_fn()
ax = plt.gca()
ax.set_facecolor(face_col)
ax.spines['bottom'].set_color('white')
ax.spines['top'].set_color('white')
ax.spines['left'].set_color('white')
ax.spines['right'].set_color('white')
ax.xaxis.label.set_color('white')
ax.yaxis.label.set_color('white')
ax.grid(alpha=0.1)
ax.title.set_color('white')
ax.tick_params(axis='x', colors='white')
ax.tick_params(axis='y', colors='white')
A use case is defined below
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=50, n_classes=2, n_features=5, random_state=27)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=27)
fig=plt.figure()
plotfigure(lambda: plt.scatter(range(0,len(y)), y, marker=".",c="orange"), fig)

Categories