How to customize individual numbers on an axis in matplotlib? - python

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)

Related

How to avoid congestion of ticks in y axis?

The figure attached here has too many ticks in y axis and is congested.I dont want to change the y axis to any other scale.I want to hide the every second number in y axis.Is this possible?,which means [5,15,25.....] will be hidden.
Is there any other approach to avoid congestion in y axis?
pl.figure(figsize=(10, 8))
pl.scatter(x=T1['Current_Sim_rcs_obj1'], y=T1['Final Mean_Range'])
pl.xlabel('Truth RCS [dBsm]')
pl.xlim(-40, 5)
pl.ylim(0, 280)
pl.grid()
pl.ylabel('RUT_Range[m]')
pl.xticks(np.arange(-45, 15, 5))
pl.yticks(np.arange(0, 281, 10))
pl.show()
I tried to add the below line to the above code,which didn't worked as expected.
pl.axes().yaxis.set_minor_locator(MultipleLocator(5))
You can use matplotlib's yticks() function to get all the ticks (locations) and labels. Then you can modify the two lists based on some criteria. For the criteria you give, we can ignore every second tick and label:
from matplotlib import pyplot as plt
plt.figure() # Create a figure
locs, labels = plt.yticks() # Get the current locations and labels
locs = locs[0::2] # Choose every other location
labels = labels[0::2] # Choose every other label
plt.yticks(locs, labels) # Set new yticks and labels
I could imagine other cases where where the criteria are based on the length of locs. In fact, that's probably what matplotlib is doing behind the scenes already. It has some heuristic which is trying to choose a good length for locs based on the size of the plot and the scale of the data.

How can I change value on Right axis? (python3/matplotlab)

When I'm plotting a single curve, I use
plt.tick_params(axis = 'y', which = 'both', labelright = True)
which shows the same value on the right axis as the left Y-axis.
Is there a way to change the value on the right axis?
As far as I've searched up to now, most threads are about a shared X-axis. But mine is a single curve, NOT shared axis curves.
I would like to show the percentage of the Y axis value to a base value on the right axis.
I appreciate your suggestions!
Even though you call it left axis and right axis, it really is one single axis. You may decide on which side of the plot to label it through the use of labelright and labelleft arguments of tick_params, which will just determine whether to show the labels or not.
In case you want to show something different on both sides of the plot you need a second axes. An easy method is to use a twinx axes. For how to do this see
Adding a second y-axis related to the first y-axis.
fig, ax = plt.subplots()
ax2 = ax.twinx()
Now it depends on how you want the two y axes to link to each other. You may share the y axes, or you may set the same limits, or you may calculate the limits of the one depending on the other.

Having axis ticks show fully for errorbar plot in Matplotlib

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.

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?

How to turn off the ticks AND marks of a matlibplot axes?

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)

Categories