How to plot y-axis to the opposite side? [duplicate] - python

This question already has answers here:
matplotlib y-axis label on right side
(4 answers)
Closed 2 years ago.
I have this chart below:
I would want the y-axis for the lower subplot to be plotted to the opposite side since that would make more sense. Is there a method for this? The ax.invert_yaxis() simply inverts the labels.
Note: For the curious, I simply used .invert_xaxis() to plot inverted bars.

I guess, what you are looking for is
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
of an axis object.
So with #meTchaikovsky's MVE code, you'll get
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(1,10,10)
y0 = np.random.randint(0,30,size=10)
fig,ax = plt.subplots(nrows=2,ncols=1,figsize=(8,6))
ax[1].set_xlim(0,30)
ax[0].barh(x,y0,color='violet')
ax[0].set_ylabel("Y-Axis")
ax[1].set_xlim(30,0)
ax[1].barh(x,y0,color='deepskyblue')
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
ax[1].set_ylabel("Y-Axis")
plt.show()

Related

X axis for plt plot python is cluttered together [duplicate]

This question already has answers here:
Matplotlib showing x-tick labels overlapping
(3 answers)
Closed 11 months ago.
plt.figure(figsize=(4,4))
aapl_data.plot.line(x='Date',y='Adj Close',title='test')
plt.ylabel('Adj Close')plt.show()
How do i declutter the X axis. I tried using figsize in the code but it does not do anything
Better show the whole code. Since I'm not sure if you have such a string: ax = plt.axes()
ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))
Try to formate the date
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))
There can be two solutions to this problem.
Increasing the width of the window. This can be achieved by:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(40,4))
fig.add_subplot(1,1,1).plot([1,2,3], [1,2,3])
plt.show()
Making the labels vertical rather than horizontal. This can be done by:
plt.xticks(range(10), rotation='vertical')

How to get rid of all ylabels of all subplots.[matplotlib] [duplicate]

This question already has an answer here:
Setting axis labels for histogram pandas
(1 answer)
Closed 2 years ago.
I would like to know how to get rid of all labels of all subplots. I have a dataframe consisting of 37 columns. Then, to make histograms for them, I wrote this code.
p_variables.plot.hist(subplots=True,layout=(5,8),figsize=(20,20),sharex=False,ylabel="")
plt.show()
I expected that all of ylabels of subplots were invisible by setting ylabel="". However, they do not disappear. Could someone give me idea how to solve this?
The output is below. I would like to get rid of Frequency labels.
You'll need to iterate over the returned axes and set the ylabel to "" explicitly.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(40, 5), columns=list("ABCDE"))
axes = df.plot.hist(subplots=True,layout=(5,8),figsize=(20,20),sharex=False)
for ax in axes.flatten():
ax.set_ylabel("")
plt.show()

matplotlib: place legend labels where each trace intercepts the right-hand y-axis [duplicate]

This question already has answers here:
How to annotate end of lines using python and matplotlib?
(3 answers)
Closed 3 years ago.
I have multiple lines plotted on an xy scatter plot
There are more than the number of colours in my palette, which means the colours start cycling.
I have played with using other palettes but the visibility suffers.
An idea I would like to explore now is to add the legend labels at the point where each line intercepts the right-hand y-axis.
Something like this:
Is this possible to achieve with matplotlib and/or seaborn?
Quick one, with use of the other answer to this question
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
names = ['foo', 'bar', 'foobar']
N_size = 100
fig, ax = plt.subplots(1, 1)
df = pd.DataFrame(map(lambda x: pd.Series(np.cumsum(np.random.rand(N_size) - 0.5), name=x), names)).T
df.plot(ax=ax)
ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
ax2.set_yticklabels(df.columns)
plt.show()

Pairplot using a hexbin [duplicate]

This question already has an answer here:
Hexbin plot in PairGrid with Seaborn
(1 answer)
Closed 3 years ago.
I would like to do a pairplot for all columns in my DataFrame; however instead of the scatter plot, I would like to produce hexbin plots (so I can better see density of points).
sns.pairplot doesn't have this option, I was wondering how it would be possible?
Paitplot plots two kinds of plot in a single canvas for all possible pairs of variable
Distribution Plot which is diagonal plots. You can set it by passing argument diag_kind : {‘auto’, ‘hist’, ‘kde’}, optional
Scatter Plots which are off-diagonal plots. Set it by using kind : {‘scatter’, ‘reg’}, optional
See here for more information.
The kind of plot which you want, you need to use sns.jointplot. You can use it as follows as suggested by #cripcate in the comment.
import numpy as np
import seaborn as sns
%matplotlib inline #extra attention at this line
sns.set(style="ticks")
rs = np.random.RandomState(11)
x = rs.gamma(2, size=1000)
y = -.5 * x + rs.normal(size=1000)
sns.jointplot(x, y, kind="hex", color="#4CB391")

Moving all x-axis tick labels a few pixels to the right (aligning rotated labels) [duplicate]

This question already has an answer here:
Moving matplotlib xticklabels by pixel value
(1 answer)
Closed 5 years ago.
I'm doing a bar plot with long labels, which I've rotated 45 degrees and set to be right-aligned. However, the tick labels are still a bit away from the ticks, making the plot look strange. How do move all the labels a few points to the right?
Here is my current code:
import seaborn as sns
import pylab as plt
plt.figure()
ax = sns.barplot(x="item", y="dist", hue="dset", data=df)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
EDIT: Please take look at the right-aligned subplot in stackoverflow.com/a/14854007/1452257 for an example. I can also copy the code/image to this post if you prefer.
From ImportanceOfBeingErnest's answer here, I got the following on translating tick labels in a general, arbitrary way:
import matplotlib.transforms as mtrans
# ...
trans = mtrans.Affine2D().translate(20, 0)
for t in ax.get_xticklabels():
t.set_transform(t.get_transform()+trans)

Categories