Restore left ticks in matplotlib - python

I have a question similar to:
Python Matplotlib Y-Axis ticks on Right Side of Plot
I fixed the problem of putting y-axis ticklabels on the right side of the plot, but I would like to restore y ticks on the left side too.
I tried with:
yax.set_ticks_position('both')
but I get:
ax0.set_ticks_position('both')
AttributeError: 'AxesSubplot' object has no attribute 'set_ticks_position'
How can I solve this problem?

You are not getting the right object on which to call set_ticks_position(). Here's a simpler way with gca():
from pylab import *
figure()
plot(arange(5))
ax = gca()
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')

In the second code sample you use ax0, which I guess is an Axes instance, in the first code sample you use yax, which presumably the axis-child of ax0.
I think you're looking for tick_params: ax0.tick_params(axis = 'y', direction = 'in')

Related

Matplotlib Python -> Plot_dendrogram Axis object

I'm building a plot_dendrogram graph and I'm struggling with the axis object. I need to create a Matplotlib axis object from 0,0.5 for the x and y axis. How do I do this?
current attempt:
plt.axis([0,.5,0,.5])
and I get the following error:
'list' object has no attribute 'set_ylim'
As the documentation states, plt.axis is a convenience function, which sets the axis limits of the current axes object.
To create the axes object, I would suggest something like this:
ax = plt.subplot(111)
ax.set_xlim([0, 0.5])
ax.set_ylim([0, 0.5])
However, I'm not sure how you got the error you posted. Even if I have not created any axes and just do:
import matplotlib.pyplot as plt
plt.axis([0,.5,0,.5])
I don't get an error.

remove colorbars from plot

I wrote some code to create a png of a raster object (self[:] = a np array).
it's supposed to be a method, to easily make a plot
Problem with the code is that it runs fine the first time,
but when i run this method multiple times i get a picture with multiple legends.
I tried to get rid of it with delaxes, but this legend is really stubborn.
Any Idea's how to solve this are welcome
Here's the code:
def plot(self,image_out,dpi=150, rotate = 60):
xur = self.xur()
xll = self.xll()
yur = self.yur()
yll = self.yll()
fig = plt.figure()
#tmp = range(len(fig.axes))
#tmp = tmp[::-1]
#for x in tmp:
# fig.delaxes(fig.axes[x])
ax = fig.add_subplot(111)
cax = ax.imshow(self[:],cmap='jet', extent = [yll,yur,xll,xur],
interpolation = 'nearest')
cbar = fig.colorbar()
plt.xticks(rotation=70)
plt.tight_layout(pad = 0.25)
plt.savefig(image_out,dpi=dpi)
return
You need to close the plot. I had this same problem
After plt.savefig, add plt.close()
A better option is to specify to colorbar which axes you would like to see it render into, see the example here.
I encountered the same problem and the answers in another post solved it
remove colorbar from figure in matplotlib
Please refer to the second answer
I had a similar problem and played around a little bit. I came up with two solutions which might be slightly more elegant:
Clear the whole figure and add the subplot (+colorbar if wanted) again.
If there's always a colorbar, you can simply update the axes with autoscale which also updates the colorbar.
I've tried this with imshow, but I guess it works similar for other plotting methods.
In particular, I used the first approach, which is to clear the figure by clf() and then re-add the axis each time.
You can remove the colorbar by its .remove() method:
cbar = fig.colorbar()
...
cbar.remove()

Matplotlib: Hiding specific y-tick labels not working when ticks on the right side of plot

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?

customizing just one side of tick marks in matplotlib using spines

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")

making errorbars not clipped in matplotlib with Python

I am using matplotlib in Python to plot a line with errorbars as follows:
plt.errorbar(xvalues, up_densities, yerr=ctl_sds, fmt='-^', lw=1.2, markersize=markersize,
markeredgecolor=up_color, color=up_color, label="My label", clip_on=False)
plt.xticks(xvalues)
I set the ticks on the x-axis using "xticks". However, the error bars of the last point in xvalues (i.e. xvalues[-1]) are clipped on the right -- meaning only half an error bar appears. This is true even with the clip_on=False option. How can I fix this, so that the error bars appear in full, even though their right side is technically outside xvalues[-1]?
thanks.
In matplotlib, most of the detailed control needs to be done through the Artists. I think this should do what you want:
import matplotlib.pyplot as plt
from random import uniform as r
x = range(10)
e = plt.errorbar(x, [r(2,10) for i in x], [r(.1,1) for i in x], capsize=8, color='r')
for b in e[1]:
b.set_clip_on(False)
plt.show()
The problem you were having is that the clip_on keyword was being used to control the markers and not the error bars. To control the errorbars, plt.errorbar returns a tuple, where the second item is a list of errorbars. So here I go through the list and turn the clipping off for each errorbar.
Is this what you mean? Do you want to redefine the horizontal limits of your plot?
plt.errorbar(range(5), [3,2,4,5,1], yerr=[0.1,0.2,0.3,0.4,0.5])
ax = plt.gca()
ax.set_xlim([-0.5,4.5])
(source: stevetjoa.com)

Categories