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'
Related
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()
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
I am trying to write a program that has a pyplot (as in matplotlib.pyplot) within a Tkinter GUI which can be updated. Basically what I want is a program with a Tkinter interface to be displaying some data on a pyplot, then when the program gets some new data I want to update the pyplot to contain the new data.
Here is a minimal example:
import numpy as np
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
plt.draw()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
What I expect to happen is, for a window to pop up with a plot containing a sine wave and a button. When I press the button a cosine wave should appear on the plot.
What actually happens when I run the program is that a window pops up with a plot containing a sine wave and a button. However when I press the button nothing happens. The plot does not seem to be updating.
I'm probably making some newbie mistake but I can't find any examples online of doing this sort of thing. What is going wrong here and how would I get what I want?
Any help would be greatly appreciated!
I figured it out, I need to call the draw() method on the figure's canvas attribute in order to get it to redraw, the corrected code is below. Also anyone who is encountering this or similar problems should probably look at matplotlib.animate if they need to be dynamically updating their pyplot
import numpy as np
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
root = tk.Tk()
fig = plt.figure(1)
plt.ion()
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)
canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()
def update():
s = np.cos(np.pi*t)
plt.plot(t,s)
#d[0].set_ydata(s)
fig.canvas.draw()
plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()
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')
I have Python 2.7 Win 32 and have installed Matplotlib, Numpy, PyParsing, Dateutil. In IDLE I place in the following 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=mdates.strpdate2num('%Y%m%d%H%M%S')
bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
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()
Running the code results in to the following:
Traceback (most recent call last):
File "C:/Users/Emanuel/Desktop/test.py", line 18, in <module>
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
NameError: name 'ax1' is not defined
Any suggestion to editing the code would be helpful.
This is because you are calling ax1 outside the method in which it has been defined it. Perhaps you should include that line in the method as well.
or else:
You can create the ax1 object outside the method and then change some of its attributes as necessary in your function by using global ax1
EDIT: It should look something like this:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
import numpy as np
ax1 = plt.subplot2grid((40,40), (0,0), rowspan=40, colspan=40)
def graphRawFX (axes1) :
date=mdates.strpdate2num('%Y%m%d%H%M%S')
bid, ask = np.loadtxt('GPBUSD1d.txt', unpack=True)
delimiter=',',
converters={0:mdates.strpdate2num('%Y%m%d%H%M%S') }
fig = plt.figure(figsize=(10,7))
axes1.plot(date,bid)
axes1.plot(date,ask)
graphRawFX(ax1)
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
plt.grid(True)
plt.show()