setting manual x-axis ticks violin plot - python-3.x

I'm trying to build a violin plot using matplotlib.
While setting the manual X-axis ticks based on the example provided here, I am failing to do so. Where am I missing out?
Here is a MWE
#!/usr/bin/env python3
import os
import numpy as np
import warnings
import matplotlib.pyplot as plt
import matplotlib.cbook
import matplotlib as mpl
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
OUTPUT_PATH=os.getcwd() + "/"
# Dots per inch for figure.
DPI = 500
def test_plot():
fig = plt.figure()
vector_size=100
bucket2 = np.random.rand(vector_size)
bucket3 = np.random.rand(vector_size)
bucket4 = np.random.rand(vector_size)
bucket5 = np.random.rand(vector_size)
bucket6 = np.random.rand(vector_size)
pos = [1,2,3,4,5]
data= [np.array(bucket2), np.array(bucket3), np.array(bucket4), np.array(bucket5), np.array(bucket6)]
axes1 = fig.add_subplot(111)
axes1.violinplot(data, pos, points=100, widths=0.7, showmeans=False, showextrema=True, showmedians=True)
axes1.set_xlabel('x-axis')
axes1.set_ylabel('y-axis')
xticks_t = ["",".1-.2", ".2-.3", ".3-.4", ".4-.5", ">.5"]
axes1.set_xticklabels(xticks_t)
axes1.set_xlim([0, 5])
axes1.spines['right'].set_visible(False)
axes1.spines['top'].set_visible(False)
axes1.xaxis.set_ticks_position('bottom')
axes1.yaxis.set_ticks_position('left')
fig.tight_layout()
file_name = 'test_violin.pdf'
fig.savefig(OUTPUT_PATH + str(file_name), bbox_inches='tight', dpi=DPI, pad_inches=0.1)
fig.clf()
plt.close()
pass
test_plot()

You can use the LaTeX expressions for the last tick to correctly display > as
xticks_t = ["",".1-.2", ".2-.3", ".3-.4", ".4-.5", r"$>.5$"]
and comment out the x-axis limits # axes1.set_xlim([0, 5])
which produces

Related

How do I get matplotlib subplot and GridSpec to position and size subplots as I want them?

I am trying to create a figure with 2x10 subplots. I would like them all to be square with a thin white space in between them, but they are coming out as rectangles (longer in height than width). The images I'm putting in each cell of the grid are all square, but the cell itself is not square so the extra space just becomes white space which creates a giant gap between the top row and the bottom row. Here's the code that shows the rectangles:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from PIL import Image
fig = plt.figure()
gs1 = GridSpec(2, 10)
for a in range(10):
ax = plt.subplot(gs1[0, a])
ax2 = plt.subplot(gs1[1, a])
plt.show()
output from above code
Imagine this but with little to no gaps in between cells and each cell is square instead of rectangular. Thanks in advance for any help!
You can use plt.tight_layout() to clean up your subplot figure. Also, play around with plt.rcParams for the figure size:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from PIL import Image
plt.rcParams["figure.figsize"] = (20,10)
fig = plt.figure()
gs1 = GridSpec(2, 10)
for a in range(10):
ax = plt.subplot(gs1[0, a])
ax2 = plt.subplot(gs1[1, a])
plt.tight_layout()
plt.show()
Output
For more control, you can use fig,ax and turn off all the labels and ticks. Then you can remove the white space between the subplots.
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from PIL import Image
plt.rcParams["figure.figsize"] = (20,4)
fig, ax = plt.subplots(2,10)
gs1 = GridSpec(2, 10)
for x in range(2):
for y in range(10):
ax[x,y].plot()
ax[x,y].tick_params(axis = 'both', bottom= False, left = False,
labelbottom = False, labelleft = False)
ax[1,0].tick_params(axis = 'both', bottom= True, left = True,
labelbottom = True, labelleft = True)
plt.subplots_adjust(wspace=0.05, hspace=0.05)
plt.show()
Output:

Matplotlib get_ylim() changing data transformation result

"get_ylim()" is changing the result of the transformation from data to display coordinates in matplotlib (I'm using version 3.2.1). Is it supposed to change axis properties? It's the same effect using "get_xlim()".
Here is my code:
import matplotlib.pyplot as plt
import numpy as np
dpi = 80
plt.rcParams.update({'font.size': 12})
fig, ax = plt.subplots(figsize=(1280/dpi, 720/dpi), dpi=dpi)
x = np.arange(200)
y = - 0.1 * x
ax.plot(x, y)
points = ax.transData.transform(np.vstack((x, y)).T).astype(int)
print(points[:5])
ax.get_ylim()
points = ax.transData.transform(np.vstack((x, y)).T).astype(int)
print(points[:5])
Both prints output different results only with the ax.get_ylim() in place.

Plotting a dot that moves along side a dispersive wave?

How would I go on about plotting a dot that moves along a wave pack/superposition. I saw this on the website and wanted to try for myself.https://blog.soton.ac.uk/soundwaves/further-concepts/2-dispersive-waves/. So I know how to animate a superpositon of two sine waves. But how would I plot a dot that moves along it? I won't post my entire code, but it looks somewhat like this
import matplotlib.pyplot as plt
import numpy as np
N = 1000
x = np.linspace(0,100,N)
wave1 = np.sin(2*x)
wave2 = np.sin(3*x)
sWave = wave1+wave2
plt.plot(x,sWave)
plt.ion()
for t in np.arange(0,400):
sWave.set_ydata(sWave)
plt.draw()
plt.pause(.1)
plt.ioff()
plt.show()
Note that this is just a quick draft of my original code.
You can add a scatter and update its data in a loop by using .set_offsets().
import matplotlib.pyplot as plt
import numpy as np
N = 1000
x = np.linspace(0, 100, N)
wave1 = np.sin(2*x)
wave2 = np.sin(3*x)
sWave = wave1 + wave2
fig, ax = plt.subplots()
ax.plot(x, sWave)
scatter = ax.scatter([], [], facecolor="red") # Initialize an empty scatter.
for t in range(N):
scatter.set_offsets((x[t], sWave[t])) # Modify that scatter's data.
fig.canvas.draw()
plt.pause(.001)

multi-line x tick labels using matplotlib

I am trying to create a plot with 2 xtick labels for the x-axis.
My code is given below. It does not create the x-ticks as I expected (In fact there is no xticks label in my pdf). I followed the code snippet given in the link
https://matplotlib.org/examples/pylab_examples/multiline.html
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rc
filename = 'small-dg-ss.pdf'
rc('mathtext', default='regular')
rc('lines',lw=2.6)
rc('lines',mew=2.4)
rc('text', usetex=True)
x = np.array([5,10,20,50])
fig, ax1 = plt.subplots(frameon=False)
disp_dcg = np.array([0.85, 0.88, 0.93, 1.0])
ax1.plot(x,disp_dcg,'bs:')
ax1.set_ylabel('GD',color='b',size=14)
ax1.set_ylim([0.7,1.02])
ax2 = ax1.twinx()
disp_gc = np.array([1.0, 0.98, 0.95, 0.92])
ax2.plot(x,disp_gc,'rv:')
ax2.set_ylabel('LS',color='r',size=14)
ax2.set_ylim([0.7,1.02])
plt.xticks([0.2,0.4,0.6,0.8], [r"$\beta = 0.1$
$\alpha = 0.99$", r"$\beta = 0.5$
$\alpha = 0.89$", r"$\beta = 0.8$
$\alpha = 0.51$", r"$\beta = 0.9$
$\alpha = 0.33"] )
fig.savefig(filename,format='pdf',transparent=True, bbox_inches='tight')
I do not want the entries in the variable x to appear in x-axis, but the ticks I explicitly specify.

How to show horizontal lines at tips of error bar plot using matplotlib?

I can generate an error-bar plot using the code below. The graph produced by the code shows vertical lines that represent the errors in y. I would like to have horizontal lines at the tips of these errors ("error bars") and am not sure how to do so.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1, 10, 10, dtype=int)
y = 2**x
yerr = np.sqrt(y)*10
fig, ax = plt.subplots()
ax.errorbar(x, y, yerr, solid_capstyle='projecting')
ax.grid(alpha=0.5, linestyle=':')
plt.show()
plt.close(fig)
The code generates the figure below. I've played with the solid_capstyle kwarg. Is there a specific kwarg that does what I am trying to do?
And as an example of what I'd like, the figure below:
In case it's relevant, I am using matplotlib 2.2.2
The argument you are looking for is capsize= in ax.errorbar(). The default is None so the length of the cap will default to the value of matplotlib.rcParams["errorbar.capsize"]. The number you give will be the length of the cap in points:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1, 10, 10, dtype=int)
y = 2**x
yerr = np.sqrt(y)*10
fig, ax = plt.subplots()
ax.errorbar(x, y, yerr, solid_capstyle='projecting', capsize=5)
ax.grid(alpha=0.5, linestyle=':')
plt.show()

Resources