Matplotlib: how to set a tick label above a plot - python

This is the sine and cosine plot I draw using matplotlib. But the tick labels are below the plot and can hardly seen.
My python code is:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(8,6), dpi=96)
plt.subplot(111)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="consine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
[r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$+\frac{\pi}{2}$', r'$+\pi$'])
plt.yticks([-1, 1],
[r'$-1$', r'$+1$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.legend(loc='upper left', frameon=False)
for label in ax.get_xticklabels()+ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='green', edgecolor='None', alpha=0.2))
plt.savefig("figures/exercise10.png", dpi=120)
plt.show()
So, how should I set a tick label above a plot?
Thank you!

Possibly you want to set the labels and the axes spines on top of the lines. This can easily be achieved with the "axes.axisbelow" rcParam.
plt.rcParams["axes.axisbelow"] = False

Related

Logarithmic Ticks on Top and Right Spine

I am trying to make a visualization with logarithmic ticks on all sides of the box.
import numpy as np
import matplotlib.pyplot as plt
x = np.logspace(2, 5, 5)
y = 0.5*x**(-1/2)
y2 = 0.01*x**(-1/2)
y3 = 0.05*x**(-1/3)
fig, ax = plt.subplots()
ax.plot(x, y, 'o-', label="One")
ax.plot(x, y2, '*-', label="Two")
ax.plot(x, y3, '--', label="Three")
ax.set(
xlabel='Input',
xlim=(1e2, 1e5),
xscale='log',
ylabel='Output',
ylim=(1e-5, 1e-1),
yscale='log',
)
ax.tick_params(top=True, right=True) # <-- This didn't work how I expected.
ax.legend(loc='lower left');
I would like the associated minor tick marks on the top and right spine.
Any advice on how to make that happen?
Use the which parameter of Axes.tick_params:
ax.tick_params(which='both', top=True, right=True)
Output:

How do you controle zorder across twinx in matplotlib?

I'm trying to control the zorder of different plots across twinx axes. How can I get the blue noisy plots to appear in the background and the orange smoothed plots to appear in the foreground in this plot?
from matplotlib import pyplot as plt
import numpy as np
from scipy.signal import savgol_filter
random = np.random.RandomState(0)
x1 = np.linspace(-10,10,500)**3 + random.normal(0, 100, size=500)
x2 = np.linspace(-10,10,500)**2 + random.normal(0, 100, size=500)
fig,ax1 = plt.subplots()
ax1.plot(x1, zorder=0)
ax1.plot(savgol_filter(x1,99,2), zorder=1)
ax2 = ax1.twinx()
ax2.plot(x2, zorder=0)
ax2.plot(savgol_filter(x2,99,2), zorder=1)
plt.show()
Similar to this thread, though not ideal, this is an approach using twiny along with twinx.
# set up plots
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax3 = ax1.twiny()
ax4 = ax2.twiny()
# background
ax1.plot(x1)
ax2.plot(x2)
# smoothed
ax3.plot(savgol_filter(x1,99,2), c='orange')
ax4.plot(savgol_filter(x2,99,2), c='orange')
# turn off extra ticks and labels
ax3.tick_params(axis='x', which='both', bottom=False, top=False)
ax4.tick_params(axis='x', which='both', bottom=False, top=False)
ax3.set_xticklabels([])
ax4.set_xticklabels([])
# fix zorder
ax1.set_zorder(1)
ax2.set_zorder(2)
ax3.set_zorder(3)
ax4.set_zorder(4)
plt.show()
Output:

how to plot subplots with colorbar on axes 2 in python

# Plotting Forward Modelling
fig1, ax = plt.subplots(2, figsize=(10, 10))
ax[0].set_title('model')
ax[0].plot(x, g, '.')
ax[0].set_xlim([min(x), max(x)])
ax[0].set_ylabel('gravity anomaly (mgal)')
coll = PolyCollection(kotak, array=drho, cmap='jet', edgecolors='none', linewidth=0.0)
ax[1].add_collection(coll)
ax[1].autoscale_view()
# coll.set_clim() # set batasan colorbar
ax[1].set_xlim(min(x), max(x))
ax[1].set_ylim(0, 1)
ax[1].invert_yaxis()
plt.plot(centroide[:, 0], centroide[:, 1], 'k.')
d = plt.colorbar(coll, ax=ax[1])
ax[1].set_ylabel('Depth (m)')
ax[1].set_xlabel('Distance (m)')
d.set_label('\u0394 \u03C1 (kg/m^3)')
plt.tight_layout()
plt.show()
and the result is:
My question is, how do I make image 1 above image 2 aligned and the colorbar is to the right of image 2?
Thank You

Bars width are wrong using log scale of x-axis

I need log scale x-axis. Here is my code:
plt.bar(critical_pressures_reversed, mercury_volume_scaled, bottom = 0, log = True, linewidth=0, align="center",width=.1)
plt.title("Mercury intrusion", fontsize=20)
plt.xlabel("Critical Pressure $P_c \, [kPa]$", fontsize=16)
plt.ylabel("Mercury volume $V_m \, [\mu m^3]$", fontsize=16)
plt.grid(b=True, which='major', color='black', linestyle='-', linewidth=1)
plt.grid(b=True, which='minor', color='gray', linestyle='-', linewidth=0.15)
frame = plt.gca()
figure = plt.gcf()
frame.set_xscale('log')
frame.set_axisbelow(True)
figure.set_size_inches(12, 6)
plt.savefig("intrusion_6n_press.png", dpi=300, bbox_inches='tight')
plt.close()
Resulting plot:
How to force pyplot to draw bars with constant width?
I am using matplotlib (1.4.2)
You could use plt.fill but the bar width should change based on the log. For instance, for a random dataset, the following lines:
import matplotlib.pyplot as plt
import numpy as np
x, y = np.random.randint(1,51,10), np.random.randint(1,51,10)
width = 1e-2
for i in range(len(x)):
plt.fill([10**(np.log10(x[i])-width), 10**(np.log10(x[i])-width), 10**(np.log10(x[i])+width), 10**(np.log10(x[i])+width)],[0, y[i], y[i], 0], 'r', alpha=0.4)
plt.bar(x,y, bottom = 0, log = True, linewidth=0, align="center",width=.1, alpha=0.4)
will produce the figure below. Everything you need to do is to choose a proper width parameter.

changing axis weight in matplotlib

How to change axis weight in matplotlib (make the axis much bolder)?
from pylab import *
x = [5,7,5,9,11,14]
y = [4,5,3,11,15,14]
scatter(x, y, s=50, color='green',marker='h')
show()
You can set the width of whats called a spine (a side of the axes) in Matplotlib:
fig, ax = plt.subplots()
ax.plot(np.random.randn(100).cumsum())
# The spines
plt.setp(ax.spines.values(), linewidth=3)
# The ticks
ax.xaxis.set_tick_params(width=3)
ax.yaxis.set_tick_params(width=3)
Use axhline, axvline:
axhline(linewidth=5, color='black')
axvline(linewidth=5, color='black')
axhline(linewidth=5, y=max(y)*1.1, color='black')
axvline(linewidth=5, x=max(x)*1.1, color='black')

Categories

Resources