In matplotlib, the axes are sometimes displayed in standard form. The numbers are shown by the ticks and something like '1e-7' appears by the axis. Is there a way to change that to a written out $\times 10^{-7}$?
I am not looking to change the labels on each individual tick. I am looking to change the text that appears once at the bottom of the axis saying '1e-7'.
The simplest answer: Use the latex mode:
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['text.usetex'] = True
x = np.arange(10000, 10011)
plt.plot(x)
plt.show()
Result:
EDIT:
Actually you don't need to use latex at all. The ScalarFormatter which is used by default has an option to use scientific notation:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
x = np.arange(10000, 10011)
fig, ax = plt.subplots(1)
ax.plot(x)
formatter = mticker.ScalarFormatter(useMathText=True)
ax.yaxis.set_major_formatter(formatter)
plt.show()
Result:
Have a look at matplotlib.ticker. It allows you control of the formatting of ticks including the labels.
Related
I do have a question with matplotlib in python. I create different figures, where every figure should have the same height to print them in a publication/poster next to each other.
If the y-axis has a label on the very top, this shrinks the height of the box with the plot. So I use MaxNLocator to remove the upper and lower y-tick. In some plots, I want to have the 1.0 as a number on the y-axis, because I have normalized data. So I need a solution, which expands in these cases the y-axis and ensures 1.0 is a y-Tick, but does not corrupt the size of the figure using tight_layout().
Here is a minimal example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0,1,num=11)
y = np.linspace(1,.42,num=11)
fig,axs = plt.subplots(1,1)
axs.plot(x,y)
locator=MaxNLocator(prune='both',nbins=5)
axs.yaxis.set_major_locator(locator)
plt.tight_layout()
fig.show()
Here is a link to a example-pdf, which shows the problems with height of upper boxline.
I tried to work with adjust_subplots() but this is of no use for me, because I vary the size of the figures and want to have same the font size all the time, which changes the margins.
Question is:
How can I use MaxNLocator and specify a number which has to be in the y-axis?
Hopefully someone of you has some advice.
Greetings,
Laenan
Assuming that you know in advance how many plots there will be in 1 row on a page one way to solve this would be to put all those plots into one figure - matplotlib will make sure they are alinged on axes:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0, 1, num=11)
y = np.linspace(1, .42, num=11)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2})
ax1.plot(x,y)
ax2.plot(x,y)
locator=MaxNLocator(prune='both', nbins=5)
ax1.yaxis.set_major_locator(locator)
# You don't need to use tight_layout and using it might give an error
# plt.tight_layout()
fig.show()
I'm very new to Python/data sets. I am not sure of the terminology to use when describing my question. As a result it's been difficult searching for answers. I have plotted a data set that ranges 0 - 20,000,000,000,000 for the y axis. Here is what I have:
However, for my assignment it should look like so:
I have tried ticklabel_format(style='plain', axis='y') which gives me:
This give me the numbers with no scientific notation and too many zeros! I'm not sure which methods I should be using to scale(?) the numbers. I've thought about operating on my raw data values but that doesn't seem right. I have looked at the documentation for matplotlib.pyplot.yscale but unless I'm missing something it doesn't seem to be what I need. Any help is appreciated. Thanks.
You can scale your data using a numpy.array and then specify the scaling in the y-axis:
import numpy as np
import matplotlib.pyplot as plt
#scale the data appropriately with numpy.array
dataset_1 = np.array(dataset_1)
scaled_dataset_1 = dataset_1/(10**9)
#plot with scaling specified in label
plt.plot(x_axis, scaled_dataset_1)
plt.ylabel('Dataset 1 (10^9)')
To change the Y-axis to exponential, you can use the following settings Please refer to this page.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter
x = np.arange(0, 200000000, 1)
fig, ax = plt.subplots(figsize=(6, 6))
ax.plot(x * 1000000, x * 100000)
ax.yaxis.set_major_formatter(ScalarFormatter(useMathText=True))
ax.ticklabel_format(style="sci", axis="y", scilimits=(0,0))
plt.show()
I am trying to put a colorbar to my image using matplotlib. The issue comes when I try to force the ticklabels to be written in scientific notation. How can I force the scientific notation (ie, 1x10^0, 2x10^0, ..., 1x10^2, and so on) in the ticks of the color bar?
Example, let's create and plot and image with its color bar:
import matplotlib as plot
import numpy as np
img = np.random.randn(300,300)
myplot = plt.imshow(img)
plt.colorbar(myplot)
plt.show()
When I do this, I get the following image:
However, I would like to see the ticklabels in scientific notation... Is there any one line command to do this? Otherwise, is there any hint out there? Thanks!
You could use colorbar's format parameter:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.ticker as ticker
img = np.random.randn(300,300)
myplot = plt.imshow(img)
def fmt(x, pos):
a, b = '{:.2e}'.format(x).split('e')
b = int(b)
return r'${} \times 10^{{{}}}$'.format(a, b)
plt.colorbar(myplot, format=ticker.FuncFormatter(fmt))
plt.show()
You can specify the format of the colorbar ticks as follows:
pl.colorbar(myplot, format='%.0e')
There is a more straightforward (but less customizable) way to get scientific notation in a ColorBar without the %.0e formatting.
Create your ColorBar:
cbar = plt.colorbar()
And call the formatter:
cbar.formatter.set_powerlimits((0, 0))
This will make the ColorBar use scientific notation. See the example figure below to see how the ColorBar will look.
The documentation for this function can be found here.
It seems that cbar.formatter.set_powerlimits((0,0)) alone in Joseph's answer does not render math format like $10^3$ yet.
Using further cbar.formatter.set_useMathText(True) gives something like $10^3$.
import matplotlib.pyplot as plt
import numpy as np
img = np.random.randn(300,300)*10**5
myplot = plt.imshow(img)
cbar = plt.colorbar(myplot)
cbar.formatter.set_powerlimits((0, 0))
# to get 10^3 instead of 1e3
cbar.formatter.set_useMathText(True)
plt.show()
generates
plot.
See the document of set_useMathText() here.
PS: Maybe this suits best for a comment. But I do not have enough reputations.
I want to format my ticks to a certain number of significant figures, AND remove the automatic offset. For the latter I am using https://stackoverflow.com/a/6654046/1021819, and for the former I would use https://stackoverflow.com/a/25750438/1021819, i.e.
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
ax.yaxis.set_major_formatter(y_formatter)
and
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
How do I combine the FormatStrFormatter and useOffset syntax?
FormatStrFormatter doesn't use an offset, so by using your second format you automatically won't have an offset.
Compare the two subplots in this example
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
fig,(ax1,ax2)=plt.subplots(2)
ax1.plot(np.arange(10000,10010,1))
ax2.plot(np.arange(10000,10010,1))
ax2.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.4e'))
plt.show()
I do have a question with matplotlib in python. I create different figures, where every figure should have the same height to print them in a publication/poster next to each other.
If the y-axis has a label on the very top, this shrinks the height of the box with the plot. So I use MaxNLocator to remove the upper and lower y-tick. In some plots, I want to have the 1.0 as a number on the y-axis, because I have normalized data. So I need a solution, which expands in these cases the y-axis and ensures 1.0 is a y-Tick, but does not corrupt the size of the figure using tight_layout().
Here is a minimal example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0,1,num=11)
y = np.linspace(1,.42,num=11)
fig,axs = plt.subplots(1,1)
axs.plot(x,y)
locator=MaxNLocator(prune='both',nbins=5)
axs.yaxis.set_major_locator(locator)
plt.tight_layout()
fig.show()
Here is a link to a example-pdf, which shows the problems with height of upper boxline.
I tried to work with adjust_subplots() but this is of no use for me, because I vary the size of the figures and want to have same the font size all the time, which changes the margins.
Question is:
How can I use MaxNLocator and specify a number which has to be in the y-axis?
Hopefully someone of you has some advice.
Greetings,
Laenan
Assuming that you know in advance how many plots there will be in 1 row on a page one way to solve this would be to put all those plots into one figure - matplotlib will make sure they are alinged on axes:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0, 1, num=11)
y = np.linspace(1, .42, num=11)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2})
ax1.plot(x,y)
ax2.plot(x,y)
locator=MaxNLocator(prune='both', nbins=5)
ax1.yaxis.set_major_locator(locator)
# You don't need to use tight_layout and using it might give an error
# plt.tight_layout()
fig.show()