Change fontsize of colorbars in matplotlib - python-2.7

I am having difficulty adjusting the font size of the ticks on the colorbar in the following code.
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111)
im = ax.pcolor(np.ma.masked_invalid(np.roll(lon, -1100, axis=1)[:2100, :3500]),
np.ma.masked_invalid(np.roll(lat, -1100, axis=1)[:2100, :3500]),
np.ma.masked_invalid(np.roll(np.absolute(zeta_Mar), -1100, axis=1)[:2100, :3500]),
cmap='Reds', norm=colors.LogNorm(vmin=1e-6, vmax=1e-4))
ax.set_xlabel('Longitude', fontsize=14)
ax.set_xlabel('Latitude', fontsize=14)
cbar_axim = fig.add_axes([0.95, 0.15, 0.03, 0.7])
cbar = fig.colorbar(im, cax=cbar_axim, ticks=[1e-6, 1e-5, 1e-4])
cbar.set_ticklabels([r'$-10^{-6}$', r'$10^{-5}$', r'$10^{-4}$'])
cbar.set_label(r'$\zeta\ [s^{-1}]$', fontsize=16)
plt.show()
Could anyone tell me the correct syntax to include the fontsize argument?

use cbar.ax.tick_params(labelsize=10)
From here and here

If I use #Yugi's answer, I will get latex errors. You can also set the fontsize with:
ticklabs = cbar.ax.get_yticklabels()
cbar.ax.set_yticklabels(ticklabs, fontsize=10)

If you are trying to increase the font size but some numbers disappear because of big size, you can do
cbar = plt.colorbar()
for t in cbar.ax.get_yticklabels():
t.set_fontsize(20)

Related

How can I add markers on a bar graph in python?

I have made a horizontal bar graph, now I need to add markers on the bars. How can I do so?
The code I have so far is shown below:
def plot_comparison():
lengths = [11380, 44547, 166616, 184373, 193068, 258004, 369582, 462795, 503099, 581158, 660724, 671812, 918449]
y_pos = np.arange(len(length))
error = np.random.rand(len(length))
plt.barh(y_pos, length, xerr=error, align='center', alpha=0.4)
plt.yticks(y_pos, length)
plt.xlabel('Lengths')
plt.title('Comparison of different cuts')
plt.show()
You can simply add a plot command, plotting the y_pos against the lengths. Make sure to specify a maker and set linestyle to "" (or "none") otherwise the markers will be connected by straight lines.
The following code may be what you're after.
import matplotlib.pyplot as plt
import numpy as np
lengths = [11380, 44547, 166616, 184373, 193068, 258004, 369582, 462795, 503099, 581158, 660724, 671812, 918449]
y_pos = np.arange(len(lengths))
error = np.array(lengths)*0.08
plt.barh(y_pos, lengths, xerr=error, align='center', alpha=0.4)
plt.plot(lengths, y_pos, marker="D", linestyle="", alpha=0.8, color="r")
plt.yticks(y_pos, lengths)
plt.xlabel('Lengths')
plt.title('Comparison of different cuts')
plt.show()

Obtaining matplotlib slider widget position from callback in non-global context

I wanted to use the matplotlib slider as seen in an example from a previous question (below) inside a GUI window (such as TkInter etc). But, in a non-global context, the variables for the plot ("spos, fig, ax") are not defined. My understanding is that because update is used as a callback function, one can't or shouldn't pass arguments.
If so, how can a plot be updated without global variables? or
How can I obtain the slider position outside the callback function?
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
t = np.arange(0.0, 100.0, 0.1)
s = np.sin(2*np.pi*t)
l, = plt.plot(t,s)
plt.axis([0, 10, -1, 1])
axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], axisbg=axcolor)
spos = Slider(axpos, 'Pos', 0.1, 90.0)
def update(val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
spos.on_changed(update)
plt.show()
Related:
1) Another related question seems to cover this topic but does not seem to address how the position of the slider is obtained.
2) A similar question was asked and solved with Slider.set_val(). It seems in my case I would need Slider.get_val() instead.
It is possible to pass more arguments to the callback function, for example with functools.partial
def update(data, val):
pos = spos.val
ax.axis([pos,pos+10,-1,1])
fig.canvas.draw_idle()
data['position'] = pos
import functools
data = dict()
spos.on_changed(functools.partial(update, data))
plt.show()
try:
print data['position']
except KeyError:
pass
A class with __call__ method could also be used as a callback.

pyglet resolution of screen into variables

is there any options how to get values height and width of screen into variables using pyglet? I am able to print it but not extract these values.
import pyglet
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_screens()
->
>>> screen
[XlibScreen(display=<pyglet.canvas.xlib.XlibDisplay object at 0x7f4644cf0990>, x=0, y=0, width=1366, height=768, xinerama=0)]
>>>
Any idea? Thanks in advance.
it should be as simple as this:
platform = pyglet.window.get_platform()
display = platform.get_default_display()
screen = display.get_default_screen()
screen_width = screen.width
screen_height = screen.height
In new versions of pyglet pyglet.window.get_platform() is deprecated/removed proof
Therefore code will look like:
display = pyglet.canvas.Display()
screen = display.get_default_screen()
screen_width = screen.width
screen_height = screen.height

How to obtain the contour plot data for each scatter points?

I have plotted a contour plot as background which represent the altitude of the area.
And 100 scatter points were set represent the real pollutant emission source. Is there a method to obtain the altitude of each point?
This is my code:
%matplotlib inline
fig=plt.figure(figsize=(16,16))
ax=plt.subplot()
xi,yi = np.linspace(195.2260,391.2260,50),
np.linspace(4108.9341,4304.9341,50)
height=np.array(list(csv.reader(open("/Users/HYF/Documents/SJZ_vis/Concentration/work/terr_grd.csv","rb"),delimiter=','))).astype('float')
cmap = cm.get_cmap(name='terrain', lut=None)
terrf = plt.contourf(xi, yi, height,100, cmap=cmap)
terr = plt.contour(xi, yi, height, 100,
colors='k',alpha=0.5
)
plt.clabel(terr, fontsize=7, inline=20)
ax.autoscale(False)
point= plt.scatter(dat_so2["xp"], dat_so2["yp"], marker='o',c="grey",s=40)
ax.autoscale(False)
for i in range(0,len(dat_so2["xp"]),1):
plt.text(dat_so2["xp"][i], dat_so2["yp"][i],
str(i),color="White",fontsize=16)
ax.set_xlim(225,275)
ax.set_ylim(4200,4260)
plt.show()
You can do this with scipy.interpolate.interp2d
For example, you could add to your code:
from scipy import interpolate
hfunc = interpolate.interp2d(xi,yi,height)
pointheights = np.zeros(dat_so2["xp"].shape)
for i,(x,y) in enumerate(zip(dat_so2["xp"],dat_so2["yp"])):
pointheights[i]=hfunc(x,y)
Putting this together with the rest of your script, and some sample data, gives this (I've simplified a couple of things here, but you get the idea):
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
from scipy import interpolate
fig=plt.figure(figsize=(8,8))
ax=plt.subplot()
#xi,yi = np.linspace(195.2260,391.2260,50),np.linspace(4108.9341,4304.9341,50)
xi,yi = np.linspace(225,275,50),np.linspace(4200,4260,50)
# A made up function of height (in place of your data)
XI,YI = np.meshgrid(xi,yi)
height = (XI-230.)**2 + (YI-4220.)**2
#height=np.array(list(csv.reader(open("/Users/HYF/Documents/SJZ_vis/Concentration/work/terr_grd.csv","rb"),delimiter=','))).astype('float')
cmap = cm.get_cmap(name='terrain', lut=None)
terrf = plt.contourf(xi, yi, height,10, cmap=cmap)
terr = plt.contour(xi, yi, height, 10,
colors='k',alpha=0.5
)
plt.clabel(terr, fontsize=7, inline=20)
ax.autoscale(False)
# Some made up sample points
dat_so2 = np.array([(230,4210),(240,4220),(250,4230),(260,4240),(270,4250)],dtype=[("xp","f4"),("yp","f4")])
point= plt.scatter(dat_so2["xp"], dat_so2["yp"], marker='o',c="grey",s=40)
# The interpolation function
hfunc = interpolate.interp2d(xi,yi,height)
# Now, for each point, lets interpolate the height
pointheights = np.zeros(dat_so2["xp"].shape)
for i,(x,y) in enumerate(zip(dat_so2["xp"],dat_so2["yp"])):
pointheights[i]=hfunc(x,y)
print pointheights
ax.autoscale(False)
for i in range(0,len(dat_so2["xp"]),1):
plt.text(dat_so2["xp"][i], dat_so2["yp"][i],
str(i),color="White",fontsize=16)
# We can also add a height label to the plot
plt.text(dat_so2["xp"][i], dat_so2["yp"][i],
"{:4.1f}".format(pointheights[i]),color="black",fontsize=16,ha='right',va='top')
ax.set_xlim(225,275)
ax.set_ylim(4200,4260)
plt.show()

Transparent pngs with Django and matplotlib

I currently have a Django project, with a view function, with code like the following (code copied from this post):
from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg
def test_matplotlib(request):
f = figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
It creates a png from a graph and serves it directly. How can I make the background of the graph transparent in this png?
Untested, but this should work. You don't have to write to an (actual) file, a file-like object should work. This code saves the image into the response.
def test_matplotlib(request):
f = figure(1, figsize=(6,6))
ax = axes([0.1, 0.1, 0.8, 0.8])
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]
explode=(0, 0.05, 0, 0)
pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
#canvas = FigureCanvasAgg(f)
response = HttpResponse(content_type='image/png')
f.savefig(response, transparent=True, format='png')
#canvas.print_png(response)
return response