Matplotlib two axes - one legend [duplicate] - python

This question already has answers here:
How do I make a single legend for many subplots?
(10 answers)
How to put the legend outside the plot
(18 answers)
Closed 6 months ago.
I've created a plot with two axes and one legend containing every line regardless of its axis.
I want to use the parameter <loc="best"> which works for all lines in axis 1. I also want it to work with axis 2. Any ideas?
My code:
lns = self.ln1 + self.ln2 + self.ln3
labels = [l.get_label() for l in lns]
self.ax1.legend(lns, labels, loc="best")
As I assign one legend only to axis one, the loc parameter also only applies to axis one. How can I change this so I still only have one legend but the loc parameter works with all axes.

Related

Reduce spacing between bars in seaborn hist plot [duplicate]

This question already has an answer here:
python matplot.hist - remove gaps between bars
(1 answer)
Closed 4 months ago.
I am plotting some data with
g = seaborn.displot(data, x=var, stat='probability')
# Set appropriate ticks
plt.xticks(np.arange(0, int(data[var].max() + 1), 1.0))
plt.show()
which is giving me the desired plot:
But I would like to compress the axis to remove the unnecessary space and I'm struggling to work out how.
You can increase the margins that determine the space added at both sides of the data limit to get the view limit. Default is 0.05.
plt.margins(x=0.5)
As pointed out by JohanC in the comment below: if your data are discrete values you may specify discrete=True or cast your data to strings to plot them as categories (in the latter case you don't need to set the ticks manually).
sns.displot(data[var].astype(str), stat='probability')

How to plot two charts on top of each other, sharing the same y axis, but having x axis mirror just for one of the charts in python [duplicate]

This question already has answers here:
matplotlib y-axis label on right side
(4 answers)
using pandas.DataFrame.melt() to plot data with seaborn
(1 answer)
seaborn multiple variables group bar plot
(1 answer)
Closed 8 months ago.
I have the chart below:
Almost everything is fine, except that I want to see the numbers close to the y axis on the right side of the chart.
They represent values that correspond to the labels on y axis as they are. I was thinking that maybe I could just do a mirror for the x axis for one of the plots, but not sure how to do it. Because if I do a mirror I end up doing it for everything.
My code is like that at the moment:
plt.figure(figsize=(12,10))
ax = sns.barplot(x='commission', y="market", hue="is_control", data= df_base.sort_values(by = dimension, ascending = False))
ax = sns.barplot(x="foods and goods", y="market", hue="is_control", data= df_base.sort_values(by = dimension, ascending = False))
plt.title("Treatment vs Control Group {}.".format(country), fontsize=14)
plt.xlabel('% of reduction', fontsize=10)
plt.ylabel('market', fontsize=10)
plt.tight_layout()
for i in ax.containers:
ax.bar_label(i,)

seaborn.lmplot with single axes labels [duplicate]

This question already has answers here:
Python Seaborn Facetgrid change xlabels
(2 answers)
Common xlabel/ylabel for matplotlib subplots
(8 answers)
How to add a shared x-label and y-label to a plot created with pandas plot
(4 answers)
One shared x-axis label for Seaborn FacetGrid subplots (layouts/spacing?)
(1 answer)
How to set common axes labels for subplots
(9 answers)
Closed last year.
What I need should be straighforward but I couldn't find a solution. Say we draw the following seaborn.lmplot:
import seaborn as sns; sns.set_theme(color_codes=True)
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", col="day", hue="day",
data=tips, col_wrap=2, height=3)
I simply want to have a single label for the x-axis and a single label for the y-axis instead of two as currently.
In other words, that the word 'tip' be printed only one time on the centre left of the graph, and that the word 'total_bill' be printed only one time on the bottom centre of the graph.
How do we do this?
EDIT: there is a similar question here One shared x-axis label for Seaborn FacetGrid subplots (layouts/spacing?) yet it is not elaborated and does not solve my issue.

Matplotlib: Multiple Histograms in One Plot [duplicate]

This question already has answers here:
How to plot in multiple subplots
(12 answers)
Closed 4 years ago.
I have several histograms that I want to include in a single figure. I know I can do this:
plt.title("Mondays")
plt.hist(mon["price"], bins=50, alpha=0.5, histtype='bar', ec='black')
plt.show()
But if I add another plt.hist(...) before calling plt.show(), matplotlib adds the second histogram on top of the first one. I'd like separate subplots for each of mon["price"], tues["price"], ..., sun["price"].
How would I go about that?
You can use subplots as in this example: matplotlob documentation 2 plots
plt.subplot(211) means: 2 rows, 1 column, 1:this is the 1st plot.
Here is an example with 4 plots: 2 rows and 2 columns:
4 plots

How to remove top value of y-axis only from Python's Matplotlib figure? [duplicate]

This question already has answers here:
Changing the tick frequency on the x or y axis
(13 answers)
Closed 7 years ago.
I am trying to plot some data using Matplotlib. My code works fine but there is a clash between my figure title and the top value of the y-axis ticks. So my question is, would anybody know how to remove the top value only from the y-axis whilst keeping everything else about the plot the same?
My code
cyp_minus=pandas.read_csv(cyp_minus_file,sep='\t')
cyp_plus=pandas.read_csv(cyp_plus_file,sep='\t')
plt.figure(9)
plt.plot(cyp_minus['Dose']*1000,cyp_minus['atRA_minus_tet'],label='Control')
plt.plot(cyp_plus['Dose']*1000,cyp_plus['Cyp26(atRA_plus_tet)'],label='RARa Overexpression')
x=plt.xlabel('[atRA] (nM)',fontsize=15)
plt.ylabel('[Cyp26A1]/beta-actin',fontsize=15)
plt.title('Effect of RARa overexpression on Cyp26A1 dose-response curve',fontsize=15)
plt.legend(loc=2,fontsize=15)
plt.rc('xtick', labelsize=20)
plt.rc('ytick', labelsize=20)
plt.savefig('Cyp26A1 DR-curve for presentation.tiff',dpi=500,bbox_extra_artists=[x], bbox_inches='tight')
Thanks
You can make your title go up so it doesn't overlap with the y top value:
plt.title('Effect of RARa overexpression on Cyp26A1 dose-response curve',fontsize=15, y=1.5) # Change y value accordinly
As an alternative to the accepted answer, if you really do want to remove the text from a tick label, you can do so like this:
yticks = plt.gca().get_yticks().tolist() # get list of ticks
yticks[-1] = '' # set last tick to empty string
ax.set_yticklabels(yticks) # set the labels

Categories

Resources