Problem Plotting Scanpy Violin Plots Next to One Another - python

I'm working on analyzing some data using scanpy and I'm trying to plot 3 violin plots next to one another but I can't seem to get it to work. I tried using subplots a few different ways but they keep getting empty charts with the violin plots in between them. I tried a few different strategies but I can't seem to get them next to one another in a 1x3 grid. Below is my latest attempt along with part of the plot showing an empty plot stacked on top of a violin plot.
plt.figure()
plt.subplot(1,3,1)
sc.pl.violin(visium, keys = 'n_genes_by_counts')
plt.subplot(1,3,2)
sc.pl.violin(visium, keys = 'total_counts')
plt.subplot(1,3,3)
sc.pl.violin(visium, keys = 'pct_counts_mt')
Sample

Try to set multi_panel = True
like this:
sc.pl.violin(visium, ['n_genes_by_counts','total_counts','pct_counts_mt'],
jitter=0.3, multi_panel=True)

Either use the flag multi_panel = True in sc.pl.violin, or the ax flag:
plt.figure()
ax1 = plt.subplot(1,3,1)
sc.pl.violin(visium, keys = 'n_genes_by_counts', ax = ax1)
ax2 = plt.subplot(1,3,2)
sc.pl.violin(visium, keys = 'total_counts', ax = ax2)
ax3 = plt.subplot(1,3,3)
sc.pl.violin(visium, keys = 'pct_counts_mt', ax = ax3)

Related

How do I remove labels from one axis in a subplot?

I am using Python 3.9 on MacOS. Shortly, I have to make a plot with 4 subplots, and they share axis. The code looks like this:
#take some data
gs = gridspec.GridSpec(2, 2, height_ratios = [3, 1])
ax0 = plt.subplot(gs[0])
#plot data, make legend, etc.
ax2 = plt.subplot(gs[2], sharex = ax0)
#plot data, make legend, etc.
#take more data
ax1 = plt.subplot(gs[1], sharey = ax0)
#plot data, make legend, etc.
ax3 = plt.subplot(gs[3], sharex = ax1, sharey = ax2)
#plot data, make legend, etc.
plt.show()
As you can see, some plots share an axis with each other. The problem is that on the x-axis everything is fine, while it is not on the y-axis (see picture). Getting to the point: how can I remove the numbers on the vertical axis of the right plot but not on the left? I've seen many posts in which the problem was solved with things like
ax.set_yticklabels([])
but that removes the numbers from the left plot as well.
Try this:
ax1.tick_params('y', labelleft=False)

Matplotlib flattens the first of two plots when I add the second plot?

Matplotlib madness...
dfin = pd.read_csv(inputfilename, sep=";", encoding='ISO-8859-1')
# create a return column
dfin['return'] = dfin['close'].shift(9) / dfin['close'].shift(12)
# create a cumulative sum column
dfin['return_cum'] = dfin['return'].cumsum()
close = dfin.iloc[:-1]['close']
test = dfin.iloc[:-1]['close'] * dfin.iloc[:-1]['return']
fig, axs = plt.subplots(figsize=(20, 10), sharex=True, sharey=True)
axs.plot(close, color='black')
axs.plot(test, color='blue')
plt.show()
plt.close()
However, when I try to run a cumulative plot of any kind, MPL flattens the first plot and plots the second relative to it:
test = dfin.iloc[:-1]['close'] * dfin.iloc[:-1]['return_cum']
I'm doing stock analysis, and trying to plot returns relative to the existing closing price. I don't understand why MPL is flatting the first plot - or how to make it stop.
Thanks for any help.
It's not flattening it per se. But the scale of the second line/plot is much bigger than the first that it shows like it's flattened.
You will need to use multiple scales (multiple y axis).
Check out this example from the matplotlib documentation.
Basically, you will need to do something like this:
...
fig, axs = plt.subplots(figsize=(20, 10), sharex=True, sharey=True)
axs.plot(close, color='black')
// same code as before above
// changed code below
ax2 = axs.twinx()
ax2.plot(test, color='blue')
fig.tight_layout()
plt.show()
plt.close()

How to switch the X-axis by the Y-axis in matplotlib? (specific case) [duplicate]

I'm trying to plot a barplot with horizontal bars. Is there any way I could do this adapting the script below?
ax = fig.add_subplot(121)
ax = df['colum_1'].plot(kind='bar',
figsize=(14,8),
title="Column1");
I know that there is the barh function, but I was wondering if there is any adaptation from the code above to do that.
Change kind from ‘bar’ to ‘barh’
ax = fig.add_subplot(121)
ax = df['colum_1'].plot(kind='barh', figsize=(14), title="Column1");
Update
To make sure that they don't overlap. Use the following approach:
fig, axs = plt.subplots(1,2)
axs[0] = df['colum_1'].plot(kind='bar', figsize=(14), title="Column1")
axs[1] = df['colum_1'].plot(kind='barh', figsize=(14), title="Column1")

Python: Draw a second y-axis on pyplot figure

I am trying to create a subplot that consists of two figures. Each of the figures shows some data plotted vs a time axis. And for each figure I want to have two y axes corresponding to two different graphs shown within the same figure.
Let's start with the data corresponding to one of the y-axes. This data is the same for each of the two figures and is generated as follows (it is fairly ugly code and if you have any suggestions as on how to improve it, please let me know!):
pwm_len = len(Time)/6
pwm_max = 255
pwm_min = 150
pwm_mid = 200
pwm_zero = 0
pwm1 = np.repeat(pwm_max, pwm_len)
pwm2 = np.repeat(pwm_min, pwm_len)
pwm3 = np.repeat(pwm_max, pwm_len)
pwm4 = np.repeat(pwm_mid, pwm_len)
pwm5 = np.repeat(pwm_max, pwm_len)
pwm6 = np.repeat(pwm_zero, pwm_len)
pwm = pwm1 + pwm2 + pwm3 + pwm4 + pwm5 + pwm6
To create the figure, I am using the following code (please note that it is not working right now, due to some wrong usage of twinx() ):
fig, axs = plt.subplots(2, sharex=True, sharey=True)
plt.subplots_adjust(hspace=0.5)
axs_pwm = axs.twinx()
axs[0].plot(Time, velocity, 'b-')
axs_pwm[0].plot(Time, pwm, 'r-')
axs[0].set_ylabel('[mm/s]')
axs_pwm[0].set_ylabel('PWM')
axs[0].grid(True)
axs[1].plot(Time, velocity_filtered, 'b-')
axs_pwm[1].plot(Time, pwm, 'r-')
axs[1].set_ylabel('[mm/s]')
axs_pwm[1]-set_ylabel('PWM')
axs[1].grid(True)
plt.show()
apparently I am using the twinx() function in a wrong way. But what is a different way to draw the second y axis?
Extending upon ImportanceOfBeingErnest's's suggestion, you need the following:
Create the twin axis for each subplot using the index 0 and 1 while using twinx()
Use the respective twin axis' object to plot data and set y-axis labels
fig, axs = plt.subplots(2, sharex=True, sharey=True)
plt.subplots_adjust(hspace=0.5)
axs_pwm1 = axs[0].twinx() # Create twin axis for the first subplot
axs[0].plot(Time, velocity, 'b-')
axs_pwm1.plot(Time, pwm, 'r-')
axs[0].set_ylabel('[mm/s]')
axs_pwm1.set_ylabel('PWM')
axs[0].grid(True)
axs_pwm2 = axs[1].twinx() # Create twin axis for the second subplot
axs[1].plot(Time, velocity_filtered, 'b-')
axs_pwm2.plot(Time, pwm, 'r-')
axs[1].set_ylabel('[mm/s]')
axs_pwm2.set_ylabel('PWM')
axs[1].grid(True)
plt.show()
Or as suggested by #SpghttCd in the comments, you can predefine all the twin axis and then use index as
ax2 = [ax.twinx() for ax in axs]
ax2[0].plot(...)
ax2[1].plot(...)

add boxplot to other graph in python

These two graphs have exactly the same x axis value of each point, is it possible to display the box whisker on top of the first graph?
I tried this:
fig1 = plt.figure()
ax = fig1.add_subplot(211)
ax.set_xscale('log')
ax.plot(x7,y7,'c+-')
ax.plot(x8,y8,'m+-')
ax.plot(x9,y9,'g+-')
ax.boxplot(dataset)
xtickNames = plt.setp(ax, xticklabels=boxx)
plt.setp(xtickNames)
The results only display the box whisker graph without the other three lines, so, I tried this instead:
fig1 = plt.figure()
ax = fig1.add_subplot(211)
ax2 = fig1.add_subplot(212)
ax.set_xscale('log')
ax.plot(x7,y7,'c+-')
ax.plot(x8,y8,'m+-')
ax.plot(x9,y9,'g+-')
ax2.set_xscale('log')
ax2.boxplot(dataset)
xtickNames = plt.setp(ax2, xticklabels=boxx)
plt.setp(xtickNames)
But I want them to be shown in the same graph, is that possible?
If you want two graphs with comparable X and Y ranges to appear one on top of the other, you can try "Hold". For example:
import pylab
pylab.plot([1,2,3,4],[4,3,2,1])
pylab.hold(True)
pylab.plot([1,2,3,4],[1,2,3,4])

Categories