I want to plot 2 subplots by using matlibplot axes. Since these two subplots have the same ylabel and ticks, I want to turn off both the ticks AND marks of the second subplot. Following is my short script:
import matplotlib.pyplot as plt
ax1=plt.axes([0.1,0.1,0.4,0.8])
ax1.plot(X1,Y1)
ax2=plt.axes([0.5,0.1,0.4,0.8])
ax2.plot(X2,Y2)
BTW, the X axis marks overlapped and not sure whether there is a neat solution or not. (A solution might be make the last mark invisible for each subplot except for the last one, but not sure how). Thanks!
A quick google and I found the answers:
plt.setp(ax2.get_yticklabels(), visible=False)
ax2.yaxis.set_tick_params(size=0)
ax1.yaxis.tick_left()
A slightly different solution might be to actually set the ticklabels to ''. The following will get rid of all the y-ticklabels and tick marks:
# This is from #pelson's answer
plt.setp(ax2.get_yticklabels(), visible=False)
# This actually hides the ticklines instead of setting their size to 0
# I can never get the size=0 setting to work, unsure why
plt.setp(ax2.get_yticklines(),visible=False)
# This hides the right side y-ticks on ax1, because I can never get tick_left() to work
# yticklines alternate sides, starting on the left and going from bottom to top
# thus, we must start with "1" for the index and select every other tickline
plt.setp(ax1.get_yticklines()[1::2],visible=False)
And now to get rid of the last tickmark and label for the x-axis
# I used a for loop only because it's shorter
for ax in [ax1, ax2]:
plt.setp(ax.get_xticklabels()[-1], visible=False)
plt.setp(ax.get_xticklines()[-2:], visible=False)
Related
I am trying to plot a graph using Matplotlib using the following code:
fig, axs = plt.subplots()
axs.set_xlim([1,5])
axs.grid()
axs.errorbar(plot1_dataerr[1],range(len(plot1_dataerr[1])),xerr = plot1_dataerr[2], fmt = 'k o')
axs.yaxis.set_ticks(np.arange(len(plot1_dataerr[1])))
axs.set_yticklabels(plot1_dataerr[0])
The variable plot1_dataerr contains the labels for the data as its 0th element, the actual means as the 1st element and the half-length of the error bars as the second element. When I run this code (along with the exact data) I get the following:
However as you can see some of the ticks on the y-axis are cut off, they should all start with 'vegetable based side dishes'. Does anyone know what I should change so that everything fits. I don't mind if some of the labels need to occupy 2 lines.
Thanks in advance!
You probably need to increase the left margin. For automatic adjustment, use
fig.tight_layout()
Else, start with
fig.subplots_adjust(left=0.4)
and decrease the value until you are happy with the result.
Using matplotlib in python. The legend overlaps with my pie chart. Tried various options for "loc" such as "best" ,1,2,3... but to no avail. Any Suggestions as to how to either exactly mention the legend position (such as giving padding from the pie chart boundaries) or at least make sure that it does not overlap?
The short answer is: You may use plt.legend's arguments loc, bbox_to_anchor and additionally bbox_transform and mode, to position the legend in an axes or figure.
The long version:
Step 1: Making sure a legend is needed.
In many cases no legend is needed at all and the information can be inferred by the context or the color directly:
If indeed the plot cannot live without a legend, proceed to step 2.
Step 2: Making sure, a pie chart is needed.
In many cases pie charts are not the best way to convey information.
If the need for a pie chart is unambiguously determined, let's proceed to place the legend.
Placing the legend
plt.legend() has two main arguments to determine the position of the legend. The most important and in itself sufficient is the loc argument.
E.g. plt.legend(loc="upper left") placed the legend such that it sits in the upper left corner of its bounding box. If no further argument is specified, this bounding box will be the entire axes.
However, we may specify our own bounding box using the bbox_to_anchor argument. If bbox_to_anchor is given a 2-tuple e.g. bbox_to_anchor=(1,1) it means that the bounding box is located at the upper right corner of the axes and has no extent. It then acts as a point relative to which the legend will be placed according to the loc argument. It will then expand out of the zero-size bounding box. E.g. if loc is "upper left", the upper left corner of the legend is at position (1,1) and the legend will expand to the right and downwards.
This concept is used for the above plot, which tells us the shocking truth about the bias in Miss Universe elections.
import matplotlib.pyplot as plt
import matplotlib.patches
total = [100]
labels = ["Earth", "Mercury", "Venus", "Mars", "Jupiter", "Saturn",
"Uranus", "Neptune", "Pluto *"]
plt.title('Origin of Miss Universe since 1952')
plt.gca().axis("equal")
pie = plt.pie(total, startangle=90, colors=[plt.cm.Set3(0)],
wedgeprops = { 'linewidth': 2, "edgecolor" :"k" })
handles = []
for i, l in enumerate(labels):
handles.append(matplotlib.patches.Patch(color=plt.cm.Set3((i)/8.), label=l))
plt.legend(handles,labels, bbox_to_anchor=(0.85,1.025), loc="upper left")
plt.gcf().text(0.93,0.04,"* out of competition since 2006", ha="right")
plt.subplots_adjust(left=0.1, bottom=0.1, right=0.75)
In order for the legend not to exceed the figure, we use plt.subplots_adjust to obtain more space between the figure edge and the axis, which can then be taken up by the legend.
There is also the option to use a 4-tuple to bbox_to_anchor. How to use or interprete this is detailed in this question: What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?
and one may then use the mode="expand" argument to make the legend fit into the specified bounding box.
There are some useful alternatives to this approach:
Using figure coordinates
Instead of specifying the legend position in axes coordinates, one may use figure coordinates. The advantage is that this will allow to simply place the legend in one corner of the figure without adjusting much of the rest. To this end, one would use the bbox_transform argument and supply the figure transformation to it. The coordinates given to bbox_to_anchor are then interpreted as figure coordinates.
plt.legend(pie[0],labels, bbox_to_anchor=(1,0), loc="lower right",
bbox_transform=plt.gcf().transFigure)
Here (1,0) is the lower right corner of the figure. Because of the default spacings between axes and figure edge, this suffices to place the legend such that it does not overlap with the pie.
In other cases, one might still need to adapt those spacings such that no overlap is seen, e.g.
title = plt.title('What slows down my computer')
title.set_ha("left")
plt.gca().axis("equal")
pie = plt.pie(total, startangle=0)
labels=["Trojans", "Viruses", "Too many open tabs", "The anti-virus software"]
plt.legend(pie[0],labels, bbox_to_anchor=(1,0.5), loc="center right", fontsize=10,
bbox_transform=plt.gcf().transFigure)
plt.subplots_adjust(left=0.0, bottom=0.1, right=0.45)
Saving the file with bbox_inches="tight"
Now there may be cases where we are more interested in the saved figure than at what is shown on the screen. We may then simply position the legend at the edge of the figure, like so
but then save it using the bbox_inches="tight" to savefig,
plt.savefig("output.png", bbox_inches="tight")
This will create a larger figure, which sits tight around the contents of the canvas:
A sophisticated approach, which allows to place the legend tightly inside the figure, without changing the figure size is presented here:
Creating figure with exact size and no padding (and legend outside the axes)
Using Subplots
An alternative is to use subplots to reserve space for the legend. In this case one subplot could take the pie chart, another subplot would contain the legend. This is shown below.
fig = plt.figure(4, figsize=(3,3))
ax = fig.add_subplot(211)
total = [4,3,2,81]
labels = ["tough working conditions", "high risk of accident",
"harsh weather", "it's not allowed to watch DVDs"]
ax.set_title('What people know about oil rigs')
ax.axis("equal")
pie = ax.pie(total, startangle=0)
ax2 = fig.add_subplot(212)
ax2.axis("off")
ax2.legend(pie[0],labels, loc="center")
I'm trying to overlay these two plots, and so far I think I might have it but the first number on the top y-axis and last number on the bottom y-axis are overlapping each other. Is there a way to individually edit each number on the y-axis so I can delete one of the two, as well make each one different from the other?
This plot ^^ is from the same code below but without the line plt.setp([a.get_yticklabels() for a in plot.axes[:-1]], visible=False)
##Plotting
plt.close('all')
pressure_plot, dyn = plt.subplots(2, sharex = True)
dyn[0].plot(s,p1_dyn,
s, p2_dyn)
dyn[1].plot(s,A)
plot.subplots_adjust(hspace = 0)
plt.setp([a.get_yticklabels() for a in plot.axes[:-1]], visible=False)
I was thinking it might be possible to use this last line here ^^ to delete one, because if you change it to yticklabels() it will remove a y axis (like seen below). But I'm not sure how to get it to individually delete one. Any ideas?
You can delete the top y value of the axis by doing:
yticks = plt.gca().get_yticks().tolist() # get list of ticks
yticks[-1] = '' # set last tick to empty string
ax.set_yticklabels(yticks)
I'm creating a subplot figure with 2 columns and a number of rows. I'm using the following code to move my tick labels and axis label to the right side for the right column (but still keeping the tick marks on both sides):
fig, ax = plt.subplots(4, 2, sharex=False, sharey=False)
fig.subplots_adjust(wspace=0, hspace=0)
for a in ax[:,1]:
a.yaxis.tick_right()
a.yaxis.set_ticks_position('both')
a.yaxis.set_label_position('right')
Then, because the subplots are close together (which is what I want, I don't want any padding in between the plots), the top and bottom y-tick labels overlap between plots. I have attempted to fix this using the method described here (this selects only those ticks that are inside the view interval - check the link for more info):
import matplotlib.transforms as mtransforms
def get_major_ticks_within_view_interval(axis):
interval = axis.get_view_interval()
ticks_in_view_interval = []
for tick, loc in zip(axis.get_major_ticks(), axis.get_major_locator()()):
if mtransforms.interval_contains(interval, loc):
ticks_in_view_interval.append(tick)
return ticks_in_view_interval
for i,a in enumerate(ax.ravel()):
nplots = len(ax.ravel())
yticks = get_major_ticks_within_view_interval(a.yaxis)
if i != 0 and i != 1:
yticks[-1].label.set_visible(False)
if i != nplots-2 and i != nplots-1:
yticks[0].label.set_visible(False)
This seems to work fine for the left column, but in the right column the overlapping ticks are still visible. Does anyone know why this happens, and how to fix it? I just can't seem to figure it out.
I have finally found the solution, so I figured I'd put it here as well in case someone ever has the same problem (or if I forget what I did, haha). I found out when I happened upon the following page: http://matplotlib.org/1.3.1/users/artists.html
What I didn't realize is that the labels on the left and the right of the y-axis can be modified independently of each other. When using yticks[0].label.set_visible(False), the label refers only to the left side labels, so the right side labels stay unchanged. To fix it, I replaced
yticks[0].label.set_visible(False)
by
yticks[0].label1.set_visible(False)
yticks[0].label2.set_visible(False)
(and the same for yticks[-1]). Now it works like a charm!
Generally I've found that problems with overlap in matplotlib can be solved by using
plt.tight_layout()
have you tried that?
I have a matplotlib horizontal bar drawn as follows:
import matplotlib.pyplot as plt
from numpy import *
from scipy import *
bars = arange(5) + 0.1
vals = rand(5)
print bars, vals
plt.figure(figsize=(5,5), dpi=100)
spines = ["bottom"]
ax = plt.subplot(1, 1, 1)
for loc, spine in ax.spines.iteritems():
if loc not in spines:
spine.set_color('none')
# don't draw ytick marks
#ax.yaxis.set_tick_params(size=0)
ax.xaxis.set_ticks_position('bottom')
plt.barh(bars, vals, align="center")
plt.savefig("test.png")
This produces this image:
I wanted to only show the xaxis, which worked using spines, but now it plots these hanging tickmarks for the right-hand yaxis. How can I remove these? id like to keep the ytickmarks on the left hand side of the plot and make them face out (direction opposite to bars). I know that I can remove the ytickmarks altogether by uncommenting the line:
#ax.yaxis.set_tick_params(size=0)
but i want to keep the ytick marks only on the left hand side. thank you.
EDIT: I achieved a solution after some trial and error though i'm sure my solution is probably not the best way to do it, so please let me know what you think still. i found that i can do:
ax.spines["left"].axis.axes.tick_params(direction="outward")
to set the tick mark direction. to get rid of the right y-axis ticks, i use:
ax.yaxis.set_ticks_position("left")
you could simply use:
ax.tick_params(axis='y', direction='out')
this will orientate the ticks as you want. And:
ax.yaxis.tick_left()
this will not plot the right ticks
You can use:
ax.tick_params(top="off")
ax.tick_params(bottom="off")
ax.tick_params(right="off")
ax.tick_params(left="off")