multi-line x tick labels using matplotlib - python-3.x

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.

Related

Adjust hspace one-sided for matplotlib subplots

My question is based on this question:
Adjust hspace for some of the subplots
Which adjusts the top plot of a number of subplots and increases the difference in hspace. I want to increase the hspace between two plots within the subplots (in my case: between plot 3 and plot4 from the top).
Here is my example:
import numpy as np
import matplotlib.pyplot as plt
noise = np.random.rand(300)
gs_top = plt.GridSpec(9, 1, hspace=0.5)
gs_base = plt.GridSpec(9, 1, hspace=0)
fig = plt.figure()
fig.patch.set_facecolor('white')
ax0 = fig.add_subplot(gs_base[0,:])
ax1 = fig.add_subplot(gs_base[1,:])
ax2 = fig.add_subplot(gs_top[2,:])
ax3 = fig.add_subplot(gs_base[3,:])
ax4 = fig.add_subplot(gs_base[4,:])
ax5 = fig.add_subplot(gs_base[5,:])
ax0.plot(noise)
ax1.plot(noise)
ax2.plot(noise)
ax3.plot(noise)
ax4.plot(noise)
ax5.plot(noise)
In the example it is shown that the hspace increases between plot 3 and 4. However, I don't want to increase the space between plot 2 and plot 3.
How can I adjust the hspace variable only on one side?
Found the answer after manipulating google by asking with various word combinations. Found this: Stackoverflow answer
In short (dirty way):
Adding a seperate axis and make it invisible.
Example:
import numpy as np
import matplotlib.pyplot as plt
noise = np.random.rand(300)
gs_base = plt.GridSpec(7, 1, hspace=0, height_ratios=[1, 1, 1, 0.8, 1,1,1])
fig = plt.figure()
fig.patch.set_facecolor('white')
ax0 = fig.add_subplot(gs_base[0,:])
ax1 = fig.add_subplot(gs_base[1,:])
ax2 = fig.add_subplot(gs_base[2,:])
ax3 = fig.add_subplot(gs_base[3,:])
ax3.set_visible(False)
ax4 = fig.add_subplot(gs_base[4,:])
ax5 = fig.add_subplot(gs_base[5,:])
ax6 = fig.add_subplot(gs_base[6,:])
ax0.plot(noise)
ax1.plot(noise)
ax2.plot(noise)
ax4.plot(noise)
ax5.plot(noise)
ax6.plot(noise)
In long (correct way):
Couldn't figure it out for the moment.

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.

setting manual x-axis ticks violin plot

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

Axis label missing

I am trying to create a 3D plot but I am having trouble with the z-axis label. It simply doesn't appear in the graph. How do I amend this? The code is as follows
# Gamma vs Current step 2
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
h = np.arange(0.1,5.1,0.1)
gamma = np.arange(0.1,5.1,0.1)
sigmaz_hgam = np.array([.009998,.03988,.08878,.15403
,.230769,.312854,.394358,.4708311,.539697879,.6,.6518698
,.696033486,.73345752165,.7651390123,.792,.814845635
,.8343567,.851098499,.865535727,.8780487,.8889486,.89848986
,.906881,.914295,.9208731,.9267338,.93197569,.93668129
,.9409202379,.94475138,.951383,.9542629,.956895,.959309
,.961526,.9635675,.96545144,.9671934,.968807,.97030539
,.9716983,.972995,.974206,.975337,.97639567,.977387,.978318
,.97919266,.98,.9807902])
mu = 1
sigmaz_hgam = mu*sigmaz_hgam
# creates an empty list for current values to be stored in
J1 = []
for i in range(sigmaz_hgam.size):
expec_sz = sigmaz_hgam[i]
J = 4*gamma[i]*(mu-expec_sz)
J1.append(J.real)
#print(J)
This part of the code is what is used to graph out which is where the problem lies
mpl.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
x = h
y = gamma
z = J1
ax.plot(x, y, z, label='Dephasing Model')
ax.legend()
ax.set_xlabel('h', fontsize=10)
ax.set_ylabel('$\gamma$')
ax.yaxis._axinfo['label']['space_factor'] = 3.0
for t in ax.zaxis.get_major_ticks(): t.label.set_fontsize(10)
# disable auto rotation
ax.zaxis.set_rotate_label(False)
ax.set_zlabel('J', fontsize=10, rotation = 0)
plt.show()
On my version of Matplotlib (2.0.2), on a Mac, I see the label (which is there – most of it is just being cropped out of the image in your case).
You could try to reduce the padding between the ticks and the label:
ax.zaxis.labelpad = 0

How to set scientific notation on axis in matplotlib

I am trying to plot a graph with two separate x-axis. One being some valve openning and the other the corresponding leak rate. I managed to make it work pretty well, though the format of that secondary axis doesn't always show scientific notations as seen on the figure down bellow
Awful overlapping labels, see the upper axis
How to force scientific notation display so that the labels wont overlap?
Here is the script I am using:
#HEADERS
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker
from matplotlib import rc
rc('font', **{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
#/HEADERS
turns = np.array([11.000, 11.500, 11.750, 12.000, 12.250, 12.375])
leak = np.array([3.89e-05, 4.63e-05, 1.67e-04, 1.45000000e-03, 8.61e-03, 1.71e-02])
pressure1 = np.array([7.9e-07, 3.0e-06, 3.5e-05, 6.1e-04, 5.1e-03, 1.8e-02])
pressure2 = np.array([8.22e-07, 8.22e-07, 8.71e-07, 1.8e-06, 1.150e-05, 7.24e-05])
pressure3 = np.array([2e-06, 2e-06, 2e-06, 1.2e-05, 1.2e-04, 6e-04])
fig = plt.figure(num='valve', figsize = (6.68, 6.68*1.3))
fig, ax1 = plt.subplots()
ax1.plot(turns, pressure1, 'r.', label= '$P_1$')
ax1.plot(turns, pressure2, 'b.', label= '$P_2$')
ax1.plot(turns, pressure3,'k.', label= '$P_3$')
plt.legend()
plt.minorticks_on()
plt.grid(b = True, which = 'major', axis = 'both')
ax1.errorbar(turns, pressure1, yerr = .4*pressure1, fmt='none', ecolor = 'k', elinewidth = 1, capsize = 1, label= '$P_{1err}$')
ax1.errorbar(turns, pressure2, yerr = .15*pressure2, fmt='none', ecolor = 'k', elinewidth = 1, capsize = 1, label= '$P_{2err}$')
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
ax1.set_yscale('log', nonposy = 'mask')
ax1.set_ylabel(r'$P$')
ax1.set_xscale('linear')
ax1.set_xlabel('Opening (turns)')
plt.minorticks_on()
#plt.grid(b = True, which = 'major', axis = 'both')
#adding a secondary x-axis above
ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim())
new_tick_locations = turns
new_tick_label = leak #dtype here ?
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(new_tick_label)
# I tried those commands from other threads but they all result in an error.
#ax2.xaxis.set_scientific(True)
#ax2.get_xaxis().set_major_formatter((matplotlib.ticker.Formatter(set_scientific(True)))
#ax2.get_xaxis().set_major_formatter().set_scientific(True)
ax2.set_xlabel(r'Leak rate (mbar$\times$L/s)')
plt.tight_layout()
#export png
plt.savefig(('export.png'), format = 'png', transparent=False, dpi = 300)
plt.show()
I'm using Python 3.6.
Thanks for your help.
Since you override the ticks, you can format them yourself and rotate them as well for more space:
new_tick_label = ['{:5.2e}'.format(x) for x in leak]
ax2.set_xticks(new_tick_locations)
ax2.set_xticklabels(new_tick_label, rotation=30)
Result:

Resources