Change matplotlib offset notation from scientific to plain - python

I want to set the formatting of the y-axis offset in my plot to non-scientific notation, but I can't find a setting to do this. Other questions and their solutions describe how to either remove the offset altogether, or set the y-ticks to scientific/plain notation; I haven't found an answer for setting the notation of the offset itself.
I've already tried using these two options, but I think they're meant for the y-ticks, not the offsets:
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
and
ax.get_yaxis().get_major_formatter().set_scientific(False)
So, the actual result is +6.3781e3, when I want +6378.1
Any way to do this?
Edit: Added example code and figure:
#!/usr/bin/env python
from matplotlib import pyplot as plt
from matplotlib import ticker
plt.rcParams['font.family'] = 'monospace'
import random
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()

You can subclass the default ScalarFormatter and replace the get_offset method, such that it would simply return the offset as it is. Note that if you wanted to make this compatible with the multiplicative "offset", this solution would need to be adapted (currently it just prints a warning).
from matplotlib import pyplot as plt
import matplotlib.ticker
import random
class PlainOffsetScalarFormatter(matplotlib.ticker.ScalarFormatter):
def get_offset(self):
if len(self.locs) == 0:
return ''
if self.orderOfMagnitude:
print("Your plot will likely be labelled incorrectly")
return self.offset
Date = range(10)
R = [6373.1+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.yaxis.set_major_formatter(PlainOffsetScalarFormatter())
ax.ticklabel_format(axis='y', style='plain', useOffset=6378.1)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
plt.show()

A way to do this is to disable the offset text itself and add your custom ax.text there as follows
from matplotlib import pyplot as plt
import random
plt.rcParams['font.family'] = 'monospace'
offset = 6378.1
Date = range(10)
R = [offset+10*random.random() for i in range(10)]
fig, ax = plt.subplots(figsize=(9,6))
ax.plot(Date,R,'-D',zorder=2,markersize=3)
ax.ticklabel_format(axis='y', style='plain', useOffset=offset)
ax.set_ylabel('Mean R (km)',fontsize='small',labelpad=1)
ax.yaxis.offsetText.set_visible(False)
ax.text(x = 0.0, y = 1.01, s = str(offset), transform=ax.transAxes)
plt.show()

Related

matplotlib.pyplot.ticklabel_format has no effect on the figure

as the title suggests, this is a straightforward question: ticklabel_format simply has no effect whatsoever on my figure.
here's the script:
import sys
import math
import yaml
import numpy as np
import matplotlib.pyplot as plt
dwarf = sys.argv[1]
pts = np.empty([100,100])
fig = plt.figure()
fig.suptitle('J value - %s'%dwarf,fontsize=18)
m = plt.imshow(pts,cmap='rainbow',extent=[-2,2,5,9])
plt.xlabel(r'$r_s [kpc]$',fontsize=18)
plt.ylabel(r'$\rho_s [M_{sun} kpc^{-3}]$',fontsize=18)
plt.ticklabel_format(style='sci',axis='x',scilimits=(-2,2))
plt.ticklabel_format(style='sci',axis='y',scilimits=(5,9))
plt.grid()
cx = plt.colorbar(m,pad=0)
cx.set_label(r'$log_{10}(J(\rho_s,r_s))$',fontsize=18)
plt.savefig('output/gridJ_%s.png'%dwarf,dpi=100,format='png')
plt.show()
on the produced plot, the ticks on the axes are simply the values dictated by extent kwarg in plt.imshow and not the nice scientific notation 10**n I would like it to have.
Any idea why it's misbehaving? Thank you
Just use matplotlib.pyplot.ylim or matplotlib.pyplot.xlim to set the limits.

Python Matplotlib add Colorbar

i've got a problem using MatlobLib with "Custom" Shapes from a shapereader. Importing and viewing inserted faces works fine, but i'm not able to place a colorbar on my figure.
I already tried several ways from the tutorial, but im quite sure there is a smart solution for this problem.
maybe somebody can help me, my current code is attached below:
from formencode.national import pycountry
import itertools
from matplotlib import cm, pyplot
from matplotlib import
from mpl_toolkits.basemap import Basemap
from numpy.dual import norm
import cartopy.crs as ccrs
import cartopy.io.shapereader as shpreader
import matplotlib as mpl
import matplotlib.colors as colors
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import numpy as np
def draw_map_for_non_normalized_data_with_alpha2_counrty_description(data, title=None):
m = Basemap()
ax = plt.axes(projection=ccrs.PlateCarree())
list = []
sum = 0
for key in data:
sum += data[key]
for key in data.keys():
new_val = (data[key]+0.00)/sum
list.append(new_val)
data[key] = new_val
#===========================================================================
# print str(min(list))
# print str(max(list))
#===========================================================================
cmap = mpl.cm.cool
colors = matplotlib.colors.Normalize(min(list)+0.0, max(list)+0.0)
labels = []
features = []
for country in shpreader.Reader(shapename).records():
a3_code = country.attributes["gu_a3"]
try :
a2_code = pycountry.countries.get(alpha3=a3_code).alpha2
except:
a2_code = ""
if a2_code in data:
val = data[a2_code]
color = cm.jet(norm(val))
print str(val) + " value for color: " + str(color)
labels.append(country.attributes['name_long'])
feat = ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=color, label=country.attributes['name_long'])
features.append(feat)
#ax.legend(features, labels, loc='upper right')
#===========================================================================
# fig = pyplot.figure(figsize=(8,3))
# ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
#===========================================================================
#cbar = m.colorbar(location='bottom')
cb1 = mpl.colorbar.ColorbarBase(ax, cmap=cmap,norm=colors,orientation='horizontal')
cb1.set_label('foo')
m.drawcoastlines()
m.drawcountries()
if title:
plt.title(title)
plt.show()
as you can see inside the code, i already tried several ways, but none of them worked for me.
maybe somebody has "the" hint for me.
thanks for help,
kind regards
As mentioned in the comments above, i would think twice about mixing Basemap and Cartopy, is there a specific reason to do so? Both are basically doing the same thing, extending Matplotlib with geographical plotting capabilities. Both are valid to use, they both have their pro's and con's.
In your example you have a Basemap axes m, a Cartopy axes ax and you are using the Pylab interface by using plt. which operates on the currently active axes. Perhaps it theoretically possible, but it seems prone to errors to me.
I cant modify your example to make it work, since the data is missing and your code is not valid Python, the indentation for the function is incorrect for example. But here is a Cartopy-only example showing how you can plot a Shapefile and use the same cmap/norm combination to add a colorbar to the axes.
One difference with your code is that you provide the axes containing the map to the ColorbarBase function, this should be a seperate axes specifically for the colorbar.
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import matplotlib as mpl
import cartopy.io.shapereader as shpreader
fig, ax = plt.subplots(figsize=(12,6),
subplot_kw={'projection': ccrs.PlateCarree()})
norm = mpl.colors.Normalize(vmin=0, vmax=1000000)
cmap = plt.cm.RdYlBu_r
for n, country in enumerate(shpreader.Reader(r'D:\ne_50m_admin_0_countries_lakes.shp').records()):
ax.add_geometries(country.geometry, ccrs.PlateCarree(),
facecolor=cmap(norm(country.attributes['gdp_md_est'])),
label=country.attributes['name'])
ax.set_title('gdp_md_est')
cax = fig.add_axes([0.95, 0.2, 0.02, 0.6])
cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, spacing='proportional')
cb.set_label('gdp_md_est')

Matplotlib pyplot axes formatter

I have an image:
Here in the y-axis I would like to get 5x10^-5 4x10^-5 and so on instead of 0.00005 0.00004.
What I have tried so far is:
fig = plt.figure()
ax = fig.add_subplot(111)
y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=True)
ax.yaxis.set_major_formatter(y_formatter)
ax.plot(m_plot,densities1,'-ro',label='0.0<z<0.5')
ax.plot(m_plot,densities2, '-bo',label='0.5<z<1.0')
ax.legend(loc='best',scatterpoints=1)
plt.legend()
plt.show()
This does not seem to work. The document page for tickers does not seem to provide a direct answer.
You can use matplotlib.ticker.FuncFormatter to choose the format of your ticks with a function as shown in the example code below. Effectively all the function is doing is converting the input (a float) into exponential notation and then replacing the 'e' with 'x10^' so you get the format that you want.
import matplotlib.pyplot as plt
import matplotlib.ticker as tick
import numpy as np
x = np.linspace(0, 10, 1000)
y = 0.000001*np.sin(10*x)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
def y_fmt(x, y):
return '{:2.2e}'.format(x).replace('e', 'x10^')
ax.yaxis.set_major_formatter(tick.FuncFormatter(y_fmt))
plt.show()
If you're willing to use exponential notation (i.e. 5.0e-6.0) however then there is a much tidier solution where you use matplotlib.ticker.FormatStrFormatter to choose a format string as shown below. The string format is given by the standard Python string formatting rules.
...
y_fmt = tick.FormatStrFormatter('%2.2e')
ax.yaxis.set_major_formatter(y_fmt)
...
Just a brief modification to the solution for better string formatting: I would recommend changing the format function to include latex formatting:
def y_fmt(x, y):
return '${:2.1e}'.format(x).replace('e', '\\cdot 10^{') + '}$'

Matplotlib Date Index Formatting

I am using matplotlib to plot some financial data. However, in its default configuration matplotlib inserts gaps in place of missing data. The documentation recommends using a date index formatter to resolve this.
However, can be seen in the examples provided on the page:
The formatting has changed from "Sept 03 2008" => "2008-09-03"
The chart no longer ends on the final sample, but rather is padded to "2008-10-14".
How can I retain this default behavior while still avoiding gaps in the data?
Edit
Sample code, from the documentation, with the desired ticks on top.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
import matplotlib.ticker as ticker
datafile = cbook.get_sample_data('aapl.csv', asfileobj=False)
print 'loading', datafile
r = mlab.csv2rec(datafile)
r.sort()
r = r[-30:] # get the last 30 days
# first we'll do it the default way, with gaps on weekends
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(r.date, r.adj_close, 'o-')
fig.autofmt_xdate()
# next we'll write a custom formatter
N = len(r)
ind = np.arange(N) # the evenly spaced plot indices
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
return r.date[thisind].strftime('%Y-%m-%d')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(ind, r.adj_close, 'o-')
ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
fig.autofmt_xdate()
plt.show()
Well, I'll answer the easy part: To get Sept 03 2008 instead of 2008-09-03 use strftime('%b %d %Y'):
def format_date(x, pos=None):
thisind = np.clip(int(x+0.5), 0, N-1)
result = r.date[thisind].strftime('%b %d %Y')
return result
PS. The last date in r.date is Oct 14 2008, so I don't think it is a bad thing to include a tick mark for it. Are you sure you don't want it?

Using Colormaps to set color of line in matplotlib

How does one set the color of a line in matplotlib with scalar values provided at run time using a colormap (say jet)? I tried a couple of different approaches here and I think I'm stumped. values[] is a storted array of scalars. curves are a set of 1-d arrays, and labels are an array of text strings. Each of the arrays have the same length.
fig = plt.figure()
ax = fig.add_subplot(111)
jet = colors.Colormap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
lines = []
for idx in range(len(curves)):
line = curves[idx]
colorVal = scalarMap.to_rgba(values[idx])
retLine, = ax.plot(line, color=colorVal)
#retLine.set_color()
lines.append(retLine)
ax.legend(lines, labels, loc='upper right')
ax.grid()
plt.show()
The error you are receiving is due to how you define jet. You are creating the base class Colormap with the name 'jet', but this is very different from getting the default definition of the 'jet' colormap. This base class should never be created directly, and only the subclasses should be instantiated.
What you've found with your example is a buggy behavior in Matplotlib. There should be a clearer error message generated when this code is run.
This is an updated version of your example:
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.cm as cmx
import numpy as np
# define some random data that emulates your indeded code:
NCURVES = 10
np.random.seed(101)
curves = [np.random.random(20) for i in range(NCURVES)]
values = range(NCURVES)
fig = plt.figure()
ax = fig.add_subplot(111)
# replace the next line
#jet = colors.Colormap('jet')
# with
jet = cm = plt.get_cmap('jet')
cNorm = colors.Normalize(vmin=0, vmax=values[-1])
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)
print scalarMap.get_clim()
lines = []
for idx in range(len(curves)):
line = curves[idx]
colorVal = scalarMap.to_rgba(values[idx])
colorText = (
'color: (%4.2f,%4.2f,%4.2f)'%(colorVal[0],colorVal[1],colorVal[2])
)
retLine, = ax.plot(line,
color=colorVal,
label=colorText)
lines.append(retLine)
#added this to get the legend to work
handles,labels = ax.get_legend_handles_labels()
ax.legend(handles, labels, loc='upper right')
ax.grid()
plt.show()
Resulting in:
Using a ScalarMappable is an improvement over the approach presented in my related answer:
creating over 20 unique legend colors using matplotlib
I thought it would be beneficial to include what I consider to be a more simple method using numpy's linspace coupled with matplotlib's cm-type object. It's possible that the above solution is for an older version. I am using the python 3.4.3, matplotlib 1.4.3, and numpy 1.9.3., and my solution is as follows.
import matplotlib.pyplot as plt
from matplotlib import cm
from numpy import linspace
start = 0.0
stop = 1.0
number_of_lines= 1000
cm_subsection = linspace(start, stop, number_of_lines)
colors = [ cm.jet(x) for x in cm_subsection ]
for i, color in enumerate(colors):
plt.axhline(i, color=color)
plt.ylabel('Line Number')
plt.show()
This results in 1000 uniquely-colored lines that span the entire cm.jet colormap as pictured below. If you run this script you'll find that you can zoom in on the individual lines.
Now say I want my 1000 line colors to just span the greenish portion between lines 400 to 600. I simply change my start and stop values to 0.4 and 0.6 and this results in using only 20% of the cm.jet color map between 0.4 and 0.6.
So in a one line summary you can create a list of rgba colors from a matplotlib.cm colormap accordingly:
colors = [ cm.jet(x) for x in linspace(start, stop, number_of_lines) ]
In this case I use the commonly invoked map named jet but you can find the complete list of colormaps available in your matplotlib version by invoking:
>>> from matplotlib import cm
>>> dir(cm)
A combination of line styles, markers, and qualitative colors from matplotlib:
import itertools
import matplotlib as mpl
import matplotlib.pyplot as plt
N = 8*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
colormap = mpl.cm.Dark2.colors # Qualitative colormap
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, colormap)):
plt.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=4);
UPDATE: Supporting not only ListedColormap, but also LinearSegmentedColormap
import itertools
import matplotlib.pyplot as plt
Ncolors = 8
#colormap = plt.cm.Dark2# ListedColormap
colormap = plt.cm.viridis# LinearSegmentedColormap
Ncolors = min(colormap.N,Ncolors)
mapcolors = [colormap(int(x*colormap.N/Ncolors)) for x in range(Ncolors)]
N = Ncolors*4+10
l_styles = ['-','--','-.',':']
m_styles = ['','.','o','^','*']
fig,ax = plt.subplots(gridspec_kw=dict(right=0.6))
for i,(marker,linestyle,color) in zip(range(N),itertools.product(m_styles,l_styles, mapcolors)):
ax.plot([0,1,2],[0,2*i,2*i], color=color, linestyle=linestyle,marker=marker,label=i)
ax.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.,ncol=3,prop={'size': 8})
U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.
Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.
from matplotlib.pyplot import cm
import numpy as np
#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:
color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
ax1.plot(x, y,c=c)
#or version 2: - faster and better:
color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)
#or version 3:
color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
c=next(color)
ax1.plot(x, y,c=c)
example of 3:
Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

Categories