When using ax.grid() and moving the spines to the middle of the plot, the grid lines go over the axes labels. Any way to stop this and move the axes labels to "front"?
EDIT: It is the ticks labels (the numbers) I'm interested in fixing, not the axis label, which can be easily moved.
EDIT: made the MWE and image match exactly
EDIT: matplotlib version 2.0.0
#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = plt.gca()
ax.minorticks_on()
ax.grid(b=True, which='major', color='k', linestyle='-',alpha=1,linewidth=1)
ax.grid(b=True, which='minor', color='k', linestyle='-',alpha=1,linewidth=1)
x = np.linspace(-5,5,100)
y = np.linspace(-5,5,100)
plt.plot(x,y)
plt.yticks([-5,-4,-3,-2,-1,0,1,2,3,4,5])
ax.spines['left'].set_position(('data', 0))
plt.show()
Related
I'm using matplotlib to produce a plot where I want to show labels on the right and left y-axis. You will notice by running the code that the grid-lines formed by the right-side y-axis appear on top of the plot line, where the left-side lines appear below. I would like them all to appear below the plot. I've tried zorder and set_axisbelow(True) without success.
Example code below:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
t = np.linspace(0,5)
x = np.exp(-t)*np.sin(2*t)
fig, ax1 = plt.subplots()
ax1.plot(t, x)
ax2 = ax1.twinx()
ax2.plot(t, x, alpha=0.0)
ax1.set_xticks([0,1,2])
ax1.set_yticks([0.1, 0.2])
ax2.set_yticks([0.3, 0.4, 0.5])
ax1.grid(True, color='lightgray')
ax2.grid(True, color='lightgray')
for a in [ax1, ax2]:
a.spines["top"].set_visible(False)
a.spines["right"].set_visible(False)
a.spines["left"].set_visible(False)
a.spines["bottom"].set_visible(False)
ax1.set_axisbelow(True)
ax2.set_axisbelow(True)
plt.savefig('fig.pdf')
plt.show()
I am trying to create two axes within one figure
fig, ax = plt.subplots(2,figsize=(20,16))
This is my first figure:
ax[0].scatter(x,y, color="brown", alpha=0.4, s=200)
ax[0].plot(x,lof, color="brown", alpha=0.4)
for the first axes I want to make the x_ticks and y_ticks bigger how can I go about this?
You can use tick_params:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,figsize=(6, 4))
ax[0].scatter([1,2,3],[1,2,3], color="brown", alpha=0.4, s=200)
ax[0].tick_params(width=2, length=4)
ax[1].tick_params(width=3, length=6)
ax[1].plot([1,2,3],[1,2,3], color="brown", alpha=0.4)
With it you can change all appearance properties of it. Here are the docs:
https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html
One way is to iterate over the major x- and y-ticks of the desired subplot (ax[0] here) and changing their font size.
Minimal representative answer
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2,figsize=(8, 4))
ax[0].scatter([1,2,3],[1,2,3], color="brown", alpha=0.4, s=200)
ax[1].plot([1,2,3],[1,2,3], color="brown", alpha=0.4)
for tick in ax[0].xaxis.get_major_ticks():
tick.label.set_fontsize(16)
for tick in ax[0].yaxis.get_major_ticks():
tick.label.set_fontsize(16)
plt.tight_layout()
plt.show()
If you don't need to differentiate between the X and Y axes, or major and minor ticks, use tick_params:
tick_size = 14
ax.tick_params(size=tick_size)
If you want to change the size of the tick labels, then you want this:
label_size = 14
ax.tick_params(labelsize=label_size)
I'm creating a bar plot in matplotlib with many, many very narrow bars. Here's some example code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(100)
y = np.random.poisson(1, size=100)
fig, ax = plt.subplots(figsize=(8, 1))
ax.bar(x, y, width=1, facecolor='red', edgecolor='white', linewidth=1)
ax.grid(color='white', linewidth=1, linestyle='-')
# some plot aesthetics
for spine in ['right', 'top', 'left']:
ax.spines[spine].set_visible(False)
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('none')
ax.yaxis.set_major_locator(plt.MultipleLocator(1))
ax.yaxis.set_major_formatter(plt.NullFormatter())
Notice that due to the finite pixel resolution, the bars vary noticeably in rendered width.
What is the best way to create this plot in matplotlib while ensuring that the rendered result has equal-width bars?
I am trying to draw a grid using matplotlib. The zorder of the grid should be behind all other lines in the plot. My problem so far is that the
minor grid lines are always drawn in front of the major grid lines i.e.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
f = plt.figure(figsize=(4,4))
ax = f.add_subplot(111)
ax.xaxis.set_minor_locator(MultipleLocator(1))
ax.xaxis.set_major_locator(MultipleLocator(10))
ax.yaxis.set_minor_locator(MultipleLocator(1))
ax.yaxis.set_major_locator(MultipleLocator(10))
majc ="#3182bd"
minc ="#deebf7"
ax.xaxis.grid(True,'minor',color=minc, ls='-', lw=0.2)
ax.yaxis.grid(True,'minor',color=minc, ls='-', lw=0.2)
ax.xaxis.grid(True,'major',color=majc, ls='-')
ax.yaxis.grid(True,'major',color=majc,ls ='-')
ax.set_axisbelow(True)
x = np.linspace(0, 30, 100)
ax.plot(x, x, 'r-', lw=0.7)
[line.set_zorder(3) for line in ax.lines]
plt.savefig('test.pdf')
Any suggestions? Thank you.
EDIT: close-up example
Even more specifically, it looks like it draws vertical majors, vertical minors, horizontal majors, horizontal minors, and plotted lines, in that order. Probably pretty deep in the matplotlib basics.
For the colors you're using, you could work around by distinguishing major and minor by alpha, not RGB. Changing two lines of your example:
ax.xaxis.grid(True,'minor',color=majc, alpha=0.2, ls='-', lw=0.2)
ax.yaxis.grid(True,'minor',color=majc, alpha=0.2, ls='-', lw=0.2)
result:
I am working on matplotlib and created some graphs like bar chart, bubble chart and others.
Can some one please explain with an example what is difference between line graph and sparkline graph and how to draw spark line graphs in python using matplotlib ?
for example with the following code
import matplotlib.pyplot as plt
import numpy as np
x=[1,2,3,4,5]
y=[5,7,2,6,2]
plt.plot(x, y)
plt.show()
the line graph generated is the following:
But I couldn't get what is the difference between a line chart and a spark lien chart for the same data. Please help me understand
A sparkline is the same as a line plot but without axes or coordinates. They can be used to show the "shape" of the data in a compact way.
You can cram several line plots in the same figure just by using subplots and changing properties of the resulting Axes for each subplot:
data = np.cumsum(np.random.rand(1000)-0.5)
data = data - np.mean(data)
fig = plt.figure()
ax1 = fig.add_subplot(411) # nrows, ncols, plot_number, top sparkline
ax1.plot(data, 'b-')
ax1.axhline(c='grey', alpha=0.5)
ax2 = fig.add_subplot(412, sharex=ax1)
ax2.plot(data, 'g-')
ax2.axhline(c='grey', alpha=0.5)
ax3 = fig.add_subplot(413, sharex=ax1)
ax3.plot(data, 'y-')
ax3.axhline(c='grey', alpha=0.5)
ax4 = fig.add_subplot(414, sharex=ax1) # bottom sparkline
ax4.plot(data, 'r-')
ax4.axhline(c='grey', alpha=0.5)
for axes in [ax1, ax2, ax3, ax4]: # remove all borders
plt.setp(axes.get_xticklabels(), visible=False)
plt.setp(axes.get_yticklabels(), visible=False)
plt.setp(axes.get_xticklines(), visible=False)
plt.setp(axes.get_yticklines(), visible=False)
plt.setp(axes.spines.values(), visible=False)
# bottom sparkline
plt.setp(ax4.get_xticklabels(), visible=True)
plt.setp(ax4.get_xticklines(), visible=True)
ax4.xaxis.tick_bottom() # but onlyt the lower x ticks not x ticks at the top
plt.tight_layout()
plt.show()
A sparkline graph is just a regular plot with all the axis removed. quite simple to do with matplotlib:
import matplotlib.pyplot as plt
import numpy as np
# create some random data
x = np.cumsum(np.random.rand(1000)-0.5)
# plot it
fig, ax = plt.subplots(1,1,figsize=(10,3))
plt.plot(x, color='k')
plt.plot(len(x)-1, x[-1], color='r', marker='o')
# remove all the axes
for k,v in ax.spines.items():
v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])
#show it
plt.show()