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)
Related
Consider this reproducable example:
import numpy as np
import matplotlib.pyplot as plt
labels = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21']
fig, axes = plt.subplots(nrows=3, ncols=3,figsize=(6, 3.5),dpi=300)
plt.subplots_adjust(wspace=0.025, hspace=0.2)
for ax in [a for b in axes for a in b]:
ax.imshow(np.random.randint(2, size=(22,42)))
ax.set_xticks([0,6,12,18,24,30,36,41])
ax.tick_params(axis='x', which='major', labelsize=3)
ax.set_yticks([])
ax.set_aspect('equal')
for ax in [item for sublist in axes for item in sublist][0::3]:
ax.set_yticks(range(len(labels)))
ax.set_yticklabels(labels,fontsize=3)
fig.savefig("example.png",bbox_inches='tight')
My issue is that even though I changed the tick font size, the lines of each tick remain the same. This looks ugly and wastes a lot of space, especially on the X axes. Any ideas how to get those lines smaller, thus that the xlabels are closer to the axis?
PS tight_layout() does not help.
Make
ax.tick_params(axis='x', which='major', labelsize=3, length=2)
and, right after,
ax.tick_params(axis='y', which='major', labelsize=3, length=2)
This will make the ticks smaller, but won't get the labels any closer to the chart.
PS: length=1 will make the ticks even smaller, obviously.
You could play with the width parameter:
ax.tick_params(axis='x', which='major', labelsize=3, width=0.1)
Instead of (line 4):
fig, axes = plt.subplots(nrows=3, ncols=3,figsize=(6, 3.5),dpi=300)
You can manipulate figsize. Example:
fig, axes = plt.subplots(nrows=3, ncols=3,figsize=(3, 2),dpi=300).
Lets's compare both outputs:
The numbers on axes are bigger than old one.
I would like to know how can I label multiple matplotlib charts, please?
If I call .xlabel(), or .ylabel() on plt directly only one of the graphs gets labelled, however if I call the functions on the figure, I get an error.
import matplotlib.pyplot as plt
import numpy as np
rng = np.random.default_rng(19680801)
N_points = 100000
dist1 = rng.standard_normal(N_points)
fig1 = plt.figure()
axis = fig1.add_subplot(1,1,1)
axis.grid()
fig2 = plt.figure()
ax = fig2.add_subplot(1,1,1)
ax.grid()
plt.xlabel('X AXIS')
plt.ylabel('Y AXIS')
axis.hist(dist1)
ax.hist(dist1)
plt.show()
You can set the labels using the Axes (axis and ax in you case) with the set_xlabel and set_ylabel methods. E.g.,
# add labels onto the first plot
axis.set_xlabel("X AXIS")
axis.set_ylabel("X AXIS")
...
ax.set_xlabel("Another X AXIS")
ax.set_ylabel("Another X AXIS")
Note that you're currently also creating two separate figures. If you want two plots on the same figure you could do:
fig, ax = plt.subplots(2, 1)
Then ax[0] will be the first axis onto which you can plot and ax[1] will be the second.
I have a figure with 11 scatter plots as subplots. I would like the legend (same across all 11 subplots) to replace the 12th subplot. Is there a way to put the legend there and have it be the same size as the subplots?
Matplotlib scatter plot of 11 subplots
Sort of a manual approach, but here it is:
You can "remove" an axis using ax.clear() and ax.set_axis_off(). Then you can create patches with specific colors and labels, and create a legend in the desired ax based on them.
Try this:
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
# Create figure with subplots
fig, axes = plt.subplots(figsize=(16, 16), ncols=4, nrows=3, sharex=True, sharey=True)
# Plot some random data
for row in axes:
for ax in row:
ax.scatter(np.random.random(5), np.random.random(5), color='green')
ax.scatter(np.random.random(2), np.random.random(2), color='red')
ax.scatter(np.random.random(3), np.random.random(3), color='orange')
ax.set_title('some title')
# Clear bottom-right ax
bottom_right_ax = axes[-1][-1]
bottom_right_ax.clear() # clears the random data I plotted previously
bottom_right_ax.set_axis_off() # removes the XY axes
# Manually create legend handles (patches)
red_patch = mpatches.Patch(color='red', label='Red data')
green_patch = mpatches.Patch(color='green', label='Green data')
orange_patch = mpatches.Patch(color='orange', label='Orange data')
# Add legend to bottom-right ax
bottom_right_ax.legend(handles=[red_patch, green_patch, orange_patch], loc='center')
# Show figure
plt.show()
Output:
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()
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()