Setting yticks Location Matplotlib - python

I'm trying to create a plot which has y axis exactly same with this :
And I'm in this situation and everything is ok until this point:
When i try this lines:
ax.set_yticks(range(20,67,10))
ax.set_yticklabels(['20','30','40','50','60'])
My graph is becoming this:
I couldn't understand how to set locations' of yticks properly.

Have you tried the following?
import numpy as np
ticks = np.linspace(20, 60, 5)
ax.set_yticks(ticks)
ax.set_yticklabels([str(int(x)) for x in ticks])

If you want numbers on the axes, make sure you plot numbers, not strings. The axis labels would then adjust automatically as desired, or you may use set_yticks and set_yticklabels as in the question.

Related

adjusting graph in maplotlib (python)

graph
how do I make this graph infill all the square around it? (I colored the part that I want to take off in yellow, for reference)
Normally I use two methods to adjust axis limits depending on a situation.
When a graph is simple, axis.set_ylim(bottom, top) method is a quick way to directly change y-axis (you might know this already).
Another way is to use matplotlib.ticker. It gives you more utilities to adjust axis ticks in your graph.
https://matplotlib.org/3.1.1/gallery/ticks_and_spines/tick-formatters.html
I'm guessing you're using a list of strings to set yaxis tick labels. You may want to set locations (float numbers) and labels (string) of y-axis ticks separatedly. Then set the limits on locations like the following snippet.
import matplotlib.pyplot as plt
import matplotlib.ticker as mt
fig, ax = plt.subplots(1,1)
ax.plot([0,1,2], [0,1,2])
ax.yaxis.set_major_locator(mt.FixedLocator([0,1,2]))
ax.yaxis.set_major_formatter(mt.FixedFormatter(["String1", "String2", "String3"]))
ax.set_ylim(bottom=0, top=2)
It gives you this: generated figure
Try setting the min and max of your x and y axes.

Modify y axis value to get correct sizing of graph matplotlib [duplicate]

I know that this question has been asked before, but I tried all the possible solutions and none of them worked for me.
So, I have a log-log plot in matplotlib, and I would like to avoid scientific notation on the x-axis.
This is my code:
from numpy import array, log, pi
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import matplotlib.ticker as mticker
plt.rc('axes.formatter', useoffset=False)
tc = array([7499680.0, 12508380.0, 23858280.0, 34877020.0, 53970660.0, 89248580.0, 161032860.0, 326814160.0, 784460200.0])
theta = array([70, 60, 50, 45, 40, 35, 30, 25, 20])
plt.scatter(theta,tc)
ax=plt.gca()
ax.set_xscale('log')
ax.set_yscale('log')
ax.xaxis.set_major_formatter(mticker.ScalarFormatter())
ax.xaxis.get_major_formatter().set_scientific(False)
ax.xaxis.get_major_formatter().set_useOffset(False)
plt.show()
And this is the output:
As you can see, the numbers on the x-axis are still in scientific notation. I would like to display them as 20, 30, 40... I tried every possible solution with no result.
Thank you very much to everyone that will help.
NB. I can't use the plt.loglog() command, because I am doing some curve fitting on the data and I need it like that.
NB2. I noticed a very weird thing happening: if I change the code to yaxis.get_mayor_formatter()..., it works on the y-axis! It is just on the x one that it's not working. How is it possible?
Edit: maybe it is not clear, but if you look at the code, there are 3 methods that should affect the display of the x-ticks: plt.rc('axes.formatter', useoffset=False), ax.xaxis.set_major_formatter(mticker.ScalarFormatter()) and ax.xaxis.get_major_formatter().set_scientific(False). They are 3 methods that should all do the trick alone, according to what I found around, but they don't. Of course I also tried them one by one and not all together.
Those are minor ticks on the x-axis (i.e. they are not on integer powers of 10), not major ticks. matplotlib automatically detemines if it should label the major or minor ticks - in this case because you don't have any major ticks displayed in the x range, the minor ticks are being labelled). So, you need to use the set_minor_formatter method:
ax.xaxis.set_minor_formatter(mticker.ScalarFormatter())
The reason it works on the y-axis is because those ticks are major ticks (i.e. on integer powers of 10), not minor ticks.
The following can be used as a workaround (original answer):
from matplotlib.ticker import StrMethodFormatter, NullFormatter
ax.yaxis.set_major_formatter(StrMethodFormatter('{x:.0f}'))
ax.yaxis.set_minor_formatter(NullFormatter())
If you want to set just the xaxis to no longer use scientific notation you need to change the fromatter and then you can set it to plain.
ax.xaxis.set_minor_formatter(mticker.ScalarFormatter())
ax.ticklabel_format(style='plain', axis='x')
If you want to disable both the offset and scientific notaion, you'd use ax.ticklabel_format(useOffset=False, style='plain')

How to remove x and y axis labels in a clustermap?

I am creating a plot based on a DataFrame:
cg = sns.clustermap(df_correlations.T)
The problem is that the x and y axis have unwanted labels in it which come from a hierarchical index. Thus I want to try and remove those labels e.g. like this:
ax = cg.fig.gca()
ax.set_xlabel('')
ax.set_ylabel('')
But this has no effect. How can I remove the labels on the x and y axis?
Without a mcve of the issue it's hard to know where the labels come from (I don't know how the dataframe needs to look like such that labels are produced, because by default there should not be any labels.) However, the labels can be set - and therefore also set to an empty string - using the known methods .set_xlabel and .set_ylabel of the heatmap axes of the cluster grid.
So if g is a ClusterGrid instance,
g = sns.clustermap(...)
you can get the heatmap axes via
ax = g.ax_heatmap
and then use any method you like to manipulate this matplotlib axes.
ax.set_xlabel("My Label")
ax.set_ylabel("")
Turn off xticklabel, and yticklabel will address your problem.
sns.clustermap(df,yticklabels=False,xticklabels=False)
try plt.axis('off'), it may solve your problem.

Rotation of colorbar tick labels in matplotlib

I would like to rotate the colorbar tick labels so that they read vertically rather than horizontally. I have tried as many variations as I can think of with cbar.ax.set_xticklabels and cbar.ax.ticklabel_format and so on with rotation='vertical' but haven't quite landed it yet.
I've provided a MWE below:
import numpy as np
import matplotlib.pyplot as plt
#example function
x,y = np.meshgrid(np.linspace(-10,10,200),np.linspace(-10,10,200))
z = x*y*np.exp(-(x+y)**2)
#array for contourf levels
clevs = np.linspace(z.min(),z.max(),50)
#array for colorbar tick labels
clevs1 =np.arange(-200,100,10)
cs1 = plt.contourf(x,y,z,clevs)
cbar = plt.colorbar(cs1, orientation="horizontal")
cbar.set_ticks(clevs1[::1])
plt.show()
Any pointers would be greatly appreciated - I'm sure this must be pretty simple...
If you're happy with tick locations and labels and only want to rotate them:
cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), rotation='vertical')
This is the idiomatic way to rotate tick labels as of Matplotlib 3.4 (and very likely earlier versions too)
cbar.ax.tick_params(rotation=45)
You can use cbar.ax.set_xticklabels to change the rotation (or set_yicklabels if you had a vertical colorbar).
cbar.ax.set_xticklabels(clevs1[::1],rotation=90)
EDIT:
To set the ticks correctly, you can search for where in your clevs1 array the first tick should be using np.argmin, and use that to index clevs1 when you set_xticklabels:
tick_start = np.argmin(abs(clevs1-clevs[0]))
cbar.ax.set_xticklabels(clevs1[tick_start:],rotation=90)

Overlapping y-axis tick label and x-axis tick label in matplotlib

If I create a plot with matplotlib using the following code:
import numpy as np
from matplotlib import pyplot as plt
xx = np.arange(0,5, .5)
yy = np.random.random( len(xx) )
plt.plot(xx,yy)
plt.imshow()
I get a result that looks like the attached image. The problem is the
bottom-most y-tick label overlaps the left-most x-tick label. This
looks unprofessional. I was wondering if there was an automatic
way to delete the bottom-most y-tick label, so I don't have
the overlap problem. The fewer lines of code, the better.
In the ticker module there is a class called MaxNLocator that can take a prune kwarg.
Using that you can remove the first tick:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
import numpy as np
xx = np.arange(0,5, .5)
yy = np.random.random( len(xx) )
plt.plot(xx,yy)
plt.gca().xaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.show()
Result:
You can pad the ticks on the x-axis:
ax.tick_params(axis='x', pad=15)
Replace ax with plt.gca() if you haven't stored the variable ax for the current figure.
You can also pad both the axes removing the axis parameter.
A very elegant way to fix the overlapping problem is increasing the padding of the x- and y-tick labels (i.e. the distance to the axis). Leaving out the corner most label might not always be wanted. In my opinion, in general it looks nice if the labels are a little bit farther from the axis than given by the default configuration.
The padding can be changed via the matplotlibrc file or in your plot script by using the commands
import matplotlib as mpl
mpl.rcParams['xtick.major.pad'] = 8
mpl.rcParams['ytick.major.pad'] = 8
Most times, a padding of 6 is also sufficient.
This is answered in detail here. Basically, you use something like this:
plt.xticks([list of tick locations], [list of tick lables])

Categories

Resources