How to make tabular legend using matplotlib and python - python-2.7

I am plotting a choropleth map in python from a shapefile and i want to customize the legend of the plot, i am using the code bellow:
import pandas as pd
import pysal as ps
import geopandas as gp
import numpy as np
import matplotlib.pyplot as plt
pth = 'outcom.shp'
tracts = gp.GeoDataFrame.from_file(pth)
ax = plot_dataframe(tracts, column='Density', scheme='QUANTILES', k=4, colormap=plt.cm.Blues, legend=True)
plt.show()
Besides, i am using a small patch that i found here http://nbviewer.ipython.org/gist/jorisvandenbossche/d4e6efedfa1e4e91ab65 in order to visualize the legend.
here's my result :
But, i need something similar to this :
so my question now, is how can i have a customized legend

You may use a plt.table as a legend.
import matplotlib.pyplot as plt
import numpy as np
valeur = np.array([.1,.45,.7])
text=[["Faible","Ng<1,5" ],["Moyenne","1,5<Ng<2,5"],[u"Elevée", "Ng>2,5"]]
colLabels = ["Exposition", u"Densité"]
tab=plt.table(cellText=text, colLabels=colLabels,
colWidths = [0.2,0.2], loc='lower right',
cellColours=plt.cm.hot_r(np.c_[valeur,valeur]))
plt.show()
In order to link this table to a contourf plot, you may do as follows:
from matplotlib import pyplot as plt
import numpy as np
a = np.sort(np.random.rand(100)).reshape(10,10)*4
levels = np.array([0,1.5,2.5,4])
sm = plt.contourf(a, levels = levels, cmap=plt.cm.hot_r )
text=[["Faible","Ng<1,5" ],["Moyenne","1,5<Ng<2,5"],[u"Elevée", "Ng>2,5"]]
colLabels = ["Exposition", u"Densité"]
col = levels[:-1] + np.diff(levels)/2.
cellcol = sm.cmap(sm.norm(np.c_[col,col]))
tax = plt.gcf().add_axes([0,0,1,1])
tab=tax.table(cellText=text, colLabels=colLabels,
colWidths = [0.2,0.2], loc='lower left',
cellColours=cellcol )
tax.axis("off")
plt.show()

Related

Django matplotlib: fname must be a PathLike or file handle

I am trying to display a plot with matplotlib and django following this and this questions, however it seems not working, I tried both solutions and only while using IO i get an empty canvas, but when I try to plot a 'real' plot I get the error in the title.
This is my view:
import django
from matplotlib.backends.backend_agg import FigureCanvasAgg as
FigureCanvas
from matplotlib.figure import Figure
import numpy as np
import matplotlib.pyplot as plt
import io
def mplimage(request):
fig = Figure()
canvas = FigureCanvas(fig)
x = np.arange(-2, 1.5, .01)
y = np.sin(np.exp(2 * x))
plt.plot(x, y)
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close(fig)
response = django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
and here the link in urls.py:
import mpl.views
url(r'mplimage.png', mpl.views.mplimage)
This works if you save the file objects as JPEG (requires PIL) instead of PNG using print_jpg() method instead of print_png().
Change:
response = django.http.HttpResponse(content_type='image/png')
canvas.print_png(response)
To:
response = HttpResponse(content_type='image/jpg')
canvas.print_jpg(response)
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np
import django
def showimage(request):
fig = Figure()
canvas = FigureCanvas(fig)
ax = fig.add_subplot(111)
x = np.arange(-2,1.5,.01)
y = np.sin(np.exp(2*x))
ax.plot(x, y)
response = HttpResponse(content_type='image/jpg')
canvas.print_jpg(response)
return response

Cannot get the pyplot multiple times

I use Embedding Python in C++, in my program, I have to run the python module many times. Unfortunately, the plt.show() only gets the figure one time, the others get the null figure
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Ellipse, Circle
import time
def show(x,y,x1,y1):
fig=plt.figure()
fig.gca().invert_yaxis()
ax1 = fig.add_subplot(111)
cir1 = Circle(xy = (x1, y1), radius=0.02, alpha=0.5)
ax1.add_patch(cir1)
print len(x)
print x1
ax1.set_title('Scatter Plot')
plt.xlabel('X')
plt.ylabel('Y')
ax1.scatter(x,y,c = 'r',marker = 'o')
plt.ion()
plt.show()
time.sleep(1)
plt.close()
return 'ok'

Trying to plot multivariate function in 3D matplotlib; returns empty figure

I am trying to plot a function F(x1,x2) in 3D matplotlib, follwoing a tutorial from here:
http://glowingpython.blogspot.com/2012/01/how-to-plot-two-variable-functions-with.html
Once I try to run the code, the figure turns out to be empty, not even the axes output is seen. I was wondering if anyone could figure out the resaon behind this behavior. I am using python 2.7
from __future__ import division
from numpy import exp,arange
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show
import math
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
from matplotlib import pylab
from numpy import arange,array,ones
from scipy import stats
import numpy
import matplotlib.ticker as mtick
import sys
import os
# the function that I'm going to plot
def z_func(x1,x2):
return exp(-(1-x1)**2 - 100*((x2-x1**2)**2))
x1 = arange(5.0,-5.0,-0.01)
x2 = arange(-5.0,5.0,0.01)
X1,X2 = meshgrid(x1, x2) # grid of point
Z = z_func(X1, X2) # evaluation of the function on the grid
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X1, X2, Z, rstride=1, cstride=1, cmap=cm.RdBu,linewidth=0, antialiased=False)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set_zlabel('z-axis')
ax.view_init(elev=25, azim=-120)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
Your code works for me. I just needed to wait till the computer will finish the computation. The long computation is because of the size of x1 and x2. Try to change these lines:
x1 = arange(5.0,-5.0,-0.01)
x2 = arange(-5.0,5.0,0.01)
to the following lines:
x1 = arange(5.0,-5.0,-0.1)
x2 = arange(-5.0,5.0,0.1)
p.s. I advise you to arrange your imports. You only need the following:
from numpy import exp, arange
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from pylab import meshgrid
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

Can't use other format for date in x axis matplotlib python

I can't seem to change the date format in x axis.
I tried different solutions that I found in internet and I keep on seeing this.
import matplotlib.pyplot as plt
import numpy as np
import datetime as dt
import matplotlib.cbook as cbook
import matplotlib.dates as dates
import pandas as pd
date = ['2015-1-23','2015-1-24','2015-1-25']
pr = [100,156,134]
date = pd.to_datetime(date)
print date
df = pd.DataFrame({'Time':date,'Value':pr})
fig,ax = plt.subplots(1)
ax.plot_date(x=df.Time,y=df.Value)
ax.grid(True)
fig.autofmt_xdate()
plt.savefig('/var/www/html/yoy.png')

Python 2.7 Value Error : need more than 2 values to unpack

I have Python 2.7 Win 32 and have installed Matplotlib, Numpy, PyParsing, Dateutil. In IDLE I place in the code:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
def graphRawFX () :
date,bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
delimiter=',',
converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
fig = plt.figure(figsize=(10,7))
ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
ax1.plot(date,bid)
ax1.plot(date,ask)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
plt.grid(True)
plt.show()
there are three variable but only two values given
date,bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')
you probably need to change that line to :
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid,ask = np.loadtxt,unpack=True,('GPBUSD1d.txt')