If i run this code in python:
titles = ctf01[0,1:]
fig = plt.figure(figsize=(11.69,8.27), dpi=100)
for num in range(len(titles)):
ax = fig.add_subplot(3,4,num+1)
ax.plot(ctf03[1:,num+1], ctf0102[:,num], 'ro')
ax.set_title(titles[num])
plt.tight_layout()
fig.text(0.5, 0.04, 'CTF12', ha='center')
fig.text(0.04, 0.5, 'CTF3', va='center', rotation='vertical')
fig.savefig("example.pdf")
i get this in the pdf file:
I would like to fix the problem with the "figure title" shown in the red circles.
If i set the 0.04 value as an negative value the title runs out of paper.
I also would like to save some space with moving the title of the subplots (green circles) into the diagram. Any idea how i can realize this?
Thanks for help.
try to add before fig.savefig("example.pdf") following line.
plt.tight_layout()
you have it in your script but it should come after text
It looks like you're trying to set the x and y labels for the whole figure, which isn't possible as these can only be set on an Axes object. Fortunately we can work around it by creating an 'invisible' subplot that fills the whole area and set the labels on this.
After plotting your subplots you would create the invisible one with:
label_ax = fig.add_subplot(111, frameon=False)
The frameon argument prevents it from drawing the box that is added by the default style. Then you tell it not to draw tick marks and make the tick labels invisible (we can't just remove them as it will mess up the spacing).
label_ax.tick_params(bottom=False, left=False, labelcolor="none")
Finally, set your labels:
label_ax.set_xlabel("CTF12")
label_ax.set_ylabel("CTF3")
You can adjust the vertical positioning of the plot titles by providing a pad argument to the set_title function. Giving a negative value will push the title into the plot, you'll need trial and error to find the value that works.
Putting it all together (with made-up data):
fig = plt.figure(figsize=(11.69, 8.27), dpi=100)
for i in range(10):
ax = fig.add_subplot(3, 4, i + 1)
ax.plot([1, 2, 3, 4, 5], "ro")
ax.set_title("Plot {}".format(i), pad=-15)
label_ax = fig.add_subplot(111, frameon=False)
label_ax.tick_params(bottom=False, left=False, labelcolor="none")
label_ax.grid(False) # In case the current style displays a grid.
label_ax.set_xlabel("CTF12")
label_ax.set_ylabel("CTF3")
fig.tight_layout()
fig.savefig("example.pdf")
Which gives:
Related
I want to make a plot with a grid of thumbnails on the left and a line plot on the right. Here is a minimal example
import numpy as np
from matplotlib import pyplot as plt
### This can change at runtime
n_grid = 4
### Grid of thumbnails
fig = plt.figure(figsize=(20,10.2))
for i in range(n_grid):
for j in range(n_grid):
ax = plt.subplot2grid(shape=(n_grid, 2*n_grid), loc=(i,j))
plt.imshow(np.random.random((16,16)))
ax.set_axis_off()
### Line plot
ax = plt.subplot2grid(shape=(n_grid, 2*n_grid), loc=(0,n_grid), rowspan=n_grid-1, colspan=n_grid)
plt.plot(np.cumsum(np.random.random(100)), label='Random Sum')
plt.xlim([0, 100])
plt.ylim(0,50)
plt.xlabel('Number', fontsize=12)
plt.ylabel('Sum', fontsize=12)
plt.figtext(0.5, 0.01, f'Unique identifier', ha='center', va='baseline')
#plt.tight_layout()
plt.subplots_adjust(left=0.01, bottom=0.03, right=0.99, top=0.99, wspace = 0.06, hspace=0.06)
plt.savefig('plot_1.png', dpi=96)
The problem is that the yticklabels and ylabel stick over the center into the area of the thumbnails. The lineplot on the right is too wide.
One common solution found on the internet is using automatic resizing with tight_layout(), so I change the last three lines to
plt.tight_layout()
#plt.subplots_adjust(left=0.01, bottom=0.03, right=0.99, top=0.99, wspace = 0.06, hspace=0.06)
plt.savefig('plot_2.png', dpi=96)
This does not rescale the lineplot, but instead makes the wspace and hspace attributes so big I get way too much whitespace between the thumbnails.
I am looking for a solution to either
Set wspace and hspace of only the right subplot, not all of them together, or
resize the lineplot to fit into the designated area, without the labels sticking out
It would seem that this is an easy problem, but despite searching for about 2 hours and digging around in the object properties with iPython I found nothing suitable. All solutions seem to change the size and padding of the subplots, not fitting a plot into the area defined with subplot2grid. The only other solution I can think of is a hack that calculates a modified aspect from the value ranges to make the lineplot always a given percentage thinner.
You can play around with subfigures. For example, if you do:
import numpy as np
from matplotlib import pyplot as plt
### This can change at runtime
n_grid = 4
### Grid of thumbnails
fig = plt.figure(figsize=(20,10.2))
# add 2 subfigures
subfigs = fig.subfigures(1, 2, wspace=0)
# add thumbnail grid into left subfig
gsLeft = subfigs[0].add_gridspec(n_grid, n_grid)
axLeft = []
for i in range(n_grid):
for j in range(n_grid):
axLeft.append(subfigs[0].add_subplot(gsLeft[i, j]))
axLeft[-1].imshow(np.random.random((16,16)))
axLeft[-1].set_axis_off()
### Line plot
gsRight = subfigs[1].add_gridspec(3, 1)
axRight = subfigs[1].add_subplot(gsRight[:2, 0])
axRight.plot(np.cumsum(np.random.random(100)), label='Random Sum')
axRight.set_xlim([0, 100])
axRight.set_ylim(0,50)
axRight.set_xlabel('Number', fontsize=12)
axRight.set_ylabel('Sum', fontsize=12)
# adjust subfigures here (play around with these to get the desired effect)
subfigs[0].subplots_adjust(wspace=0.03, hspace=0.03, bottom=0.05, top=0.95, left=0.05, right=0.95)
subfigs[1].subplots_adjust(left=0.01)
# add title (here I've had to add it to the left figure, so it's not centred,
# in my test adding it to the figure itself meant it was not visible, although
# the example in the Matplotlib docs suggests it should work!)
# fig.suptitle(f'Unique identifier', x=0.5, y=0.025, ha='center', va='baseline')
subfigs[0].suptitle(f'Unique identifier', x=0.5, y=0.025, ha='center', va='baseline')
fig.savefig("plot_1.png", dpi=150)
This gives:
but you can play around with the values to adjust it as you like.
I have a very customized subplot set up.
fig = plt.figure(figsize=(12, 10))
gs = fig.add_gridspec(nrows=2, ncols=2, width_ratios=[3, 1])
ax = fig.add_subplot(gs[:, 0])
ax3 = fig.add_subplot(gs[-1, -1])
ax4=fig.add_subplot(gs[0, 1])
This sets up 3 slots for plotting: one that takes up half the space on the left, and two smaller ones on the right. However, I only want the bottom right to actually be a plot. I want the top right to be the space where the legend for the larger plot on the left to go. I could just use the axes from ax to do this, but that shifts the whole plotting space off. Instead I thought of trying to just create ax4 and place the ax legend there.
lines = []
labels = []
for ax in fig.get_axes():
ln, la = ax.get_legend_handles_labels()
lines.extend(ln)
labels.extend(la)
legend = ax4.legend(lines, labels, labelspacing=0.1, loc=(-0.3,0.6), fontsize='xx-large')
fig.tight_layout()
This puts the legend exactly where I want it, but the blank figure shows up, which I don't want. Is it possible to accomplish what I want using this method? If not, what is my alternative? Picture below to better understand.
You can use ax4.axis('off') to make axis 4 invisible if you want to stick to your approach.
However, I don't see why you don't just skip creating axis 4 and just use fig.legend() instead of ax.legend(). Then the legend is placed outside the axis and you can then control the exact position just as you already did with the loc keyword.
In this question, they answer how to correctly use grid with imshow with matplotlib. I am trying to do the same as they do, but I want to remove all ticks (x and y). When I try to do it, it also eliminates the grid and I just the image displayed without grid and ticks. My code is:
fig, ax = plt.subplots()
data = np.random.rand(20,20)
ax.imshow(data)
ax.set_xticks(np.arange(20))
ax.set_xticklabels(np.arange(20))
ax.set_xticks(np.arange(20)+0.5, minor=True)
ax.grid(which='minor',color='w',axis='x',linewidth=6)
ax.axes.xaxis.set_visible(False)
ax.axes.yaxis.set_visible(False)
plt.show()
Does anyone how to remove the ticks while keeping the grid (along the x axis in my case)?
Removing the axes (via set_visible(False)) will also remove the grid.
However, there's a workaround setting both spines and tick marks/labels to be invisible individually:
fig, ax = plt.subplots()
data = np.random.rand(20,20)
ax.imshow(data)
ax.set_xticks(np.arange(20))
ax.set_xticklabels(np.arange(20))
ax.set_xticks(np.arange(20)+0.5, minor=True)
ax.grid(which='minor',color='w',axis='x',linewidth=6)
# set axis spines (the box around the plot) to be invisible
plt.setp(ax.spines.values(), alpha = 0)
# set both tick marks and tick labels to size 0
ax.tick_params(which = 'both', size = 0, labelsize = 0)
plt.show()
Gives you output as:
Note, you might need to adjust xlim/ylim and grid parameters to fit your needs.
This is not perfect, but you can just set the tick label as an empty list.
ax.axes.get_xaxis().set_ticks([])
ax.axes.get_yaxis().set_ticks([])
Only the minor xticks, used in the grid, remain.
I am trying to change location of plot legend. Below what I've got for now.
var_list=powiaty_cols[powiaty_cols.str.contains("apart_bel_40")]
for var in var_list:
fig = plt.figure(figsize=(25, 25))
ax = plt.gca()
powiaty.plot(column=var,cmap='Reds', categorical=True,
legend=True, ax=ax,edgecolor='black')
ax.legend(loc='best')
This code is plotting figure but without legend. I've received errors as follows:
No handles with labels found to put in legend.
No handles with labels found to put in legend.
No handles with labels found to put in legend.
No handles with labels found to put in legend.
But without part 'ax.legend(loc='best')' I can get my plot but legend is in upper left corner. Plotted column is filled with integer from 1 to 5. Similar issue is when I'm trying to change size of legend.
Could maybe somebody help in this?
I don't know what powiaty is, but my guess is that you need to get the Axes object back so you can continue modifying it. Try:
ax = powiaty.plot(column=var, cmap='Reds', categorical=True,
legend=True, ax=ax, edgecolor='black'
)
For me worked:
leg = ax.get_legend()
leg.set_bbox_to_anchor((0., 0.1, 0.2, 0.2))
I have the following plot:
dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1))
Which displays this:
I want to remove all of the borders of the chart and legend i.e. the box around the chart (leaving the axis numbers like 2015 and 6000 etc)
All of the examples I find refer to spines and 'ax', however I have not built my chart using fig = plt.figure() etc.
Anyone know how to do it?
You can remove the border of the legend by using the argument frameon=False in the call to plt.legend().
If you only have one figure and axes active, then you can use plt.gca() to get the current axes. Alternatively df.plot.bar returns an axes object (which I would suggest using because plt.gca() might get confusing when working with multiple figures). Therefore you can set the visibility of the spines to False:
ax = dfA.plot.bar(stacked=True, color=[colorDict.get(x, '#333333') for x in
dfA.columns],figsize=(10,8))
plt.legend(loc='upper right', bbox_to_anchor=(1.4, 1), frameon=False)
for spine in ax.spines:
ax.spines[spine].set_visible(False)
# Color of the spines can also be set to none, suggested in the comments by ScoutEU
# ax.spines[spine].set_color("None")