Plotting date data with pcolor - matplotlib

I have data like this:
dates = ['1874-05-02', '1874-05-03', '1874-05-04',
'1874-05-05', '1874-05-06','1874-05-07']
data1 = ['-7.000', '7.000', '2.000', '11.600', '13.500', '-13.500']
data2 = ['0.000', '25.000', '0.000', '75.000', '12.000', '22.000']
and I need to draw a diagram where dates are on x-axis and data1 on y-axis. Data2 is needed to draw dots in diagram and they should all be in differend colours corresponding their values. So how can I do this with pcolor or pcolormesh?
Here is an example-code I found from http://matplotlib.org/examples/pylab_examples/pcolor_demo.html and I was wondering could I get anything like this out with my data? Here is another link to demonstrate what I'm supposed to do: https://dl.dropboxusercontent.com/u/47527320/diagram.jpg. Can I get a diagram like this with pcolor?
import matplotlib.pyplot as plt
import numpy as np
dx, dy = 0.15, 0.05
y, x = np.mgrid[slice(-3, 3 + dy, dy),slice(-3, 3 + dx, dx)]
z = (1 - x / 2. + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)
z = z[:-1, :-1]
z_min, z_max = -np.abs(z).max(), np.abs(z).max()
plt.subplot(2, 2, 1)
plt.pcolor(x, y, z, cmap='RdBu', vmin=z_min, vmax=z_max)
plt.title('pcolor')
plt.axis([x.min(), x.max(), y.min(), y.max()])
plt.colorbar()
plt.show()

A scatter plot will give what you describe.
import numpy as np
import pylab as plt
import datetime
dt = datetime.datetime
dates = [dt(1874,05,02), dt(1874,05,03), dt(1874,05,04), dt(1874,05,05), dt(1874,05,06),dt(1874,05,07)]
data1 = [-7.000, 7.000, 2.000, 11.600, 13.500, -13.500]
data2 = [0.000, 25.000, 0.000, 75.000, 12.000, 22.000]
plt.scatter(dates, data1, c=data2, s=400)
plt.show()
There was some discussion in the comments about needing 2D data, but I think that was due to lack of clarity of what you were looking for. The types of plots in your mpl example link and your sketch are completely different in nature. Take a look through the mpl gallery page and you'll see that the ones like your sketch (and that also match the structure of your data well) are using a scatter plot.
There are lots of options here for how to handle the dates and colors, but this should get you started.

Related

Connecting point without continus boundaries

I want to plot trajectories, without connecting the points from boundaries. Attached an image of what i mean.
My code:
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# import polygon as poly
x, y = np.loadtxt('c55.txt', delimiter=' ', unpack=True)
plt.plot(x, y, '.' ,color = 'k' , markersize=0.5)
#for i in range(1, len(x),1):
#if abs(x[i]-x[i+1])>300:
plt.plot(x,y,'-o',color='red',ms=5,label="Window 1")
plt.show()
Your x-values go several times from low to high. plt.plot connects all points in the order they are encountered in the x and y arrays.
The following approach firsts looks for the indices where the x-values start again (so, where the difference of successive x's isn't positive).
These indices are then used to draw the separate curves.
from matplotlib.colors import ListedColormap
import numpy as np
# first create some test data a bit similar to the given ones.
x = np.tile(np.linspace(-3, 3, 20), 4)
y = np.cos(x) + np.repeat(np.linspace(-3, 3, 4), 20)
fig, axs = plt.subplots(ncols=2, figsize=(15, 4))
# plotting the test data without change
axs[0].plot(x, y, '-o')
bounds = np.argwhere(np.diff(x) < 0).squeeze() # find the boundaries
bounds = np.concatenate([[0], bounds + 1, [len(x)]]) # additional boundaries for the first and last point
for b0, b1 in zip(bounds[:-1], bounds[1:]):
axs[1].plot(x[b0:b1], y[b0:b1], '-o') # use '-ro' for only red curves
plt.show()

matplotib 3D figure showing surface plus contours with parts hidden correctly?

I would like to draw a surface and some of its iso-z contours, using the plot_surface and contour3D functions of mplot3D. Here is an example (I would like to use it to illustrate Lagrange points in physics) :
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
epsilon, r1 = 0.3, 1
r2 = epsilon*r1
Omega2 = 1/(r1*pow(r1+r2, 2))
u = np.linspace(-2, 2, 100)
x , y = np.meshgrid(u, u)
z = -epsilon/np.sqrt(np.power(x-r1, 2)+ np.power(y, 2)) - 1/np.sqrt(np.power(x+r2, 2)+ np.power(y, 2)) - 0.5*Omega2*(np.power(x, 2) + np.power(y, 2))
z = np.clip(z, -3, 0)
ax.plot_surface(x, y, z, rstride=1, cstride=1, antialiased=True, color="whitesmoke")
ax.contour3D(x, y, z+0.01, levels=np.arange(-2, -1, 0.1))
plt.show()
In the resulting plot, the contours do not show properly :
Image obtained by the code
and as the figure is interactively rotated, they randomly appear and disappear, with a wrong estimation of what part should be hidden by the surface :
Example of figure obtained by interactive rotation
This had been noticed before 4 years ago but no solution had been suggested. Hence my questions :
is it still, 4 years after, considered as a limitation of the plotting capabilities of matplolib ? And is there an alternative way, using some other graphical library ?

Matplotlib 3d barplot failing to draw just one face

import numpy as np
import matplotlib.pyplot as plt
x, y = np.array([[x, y] for x in range(5) for y in range(x+1)]).T
z = 1/ (5*x + 5)
fig = plt.figure()
ax = fig.gca(projection = '3d')
ax.bar3d(x, y, np.zeros_like(z), dx = 1, dy = 1, dz = z)
yields
How do I get the face at (1,0) to display properly?
There is currently no good solution to this. Fortunately though, it happens only for some viewing angles. So you can choose an angle where it plots fine, e.g.
ax.view_init(azim=-60, elev=25)

Get Value from Contourplot - Python Matplotlib

i have a problem with my contourplot. I have messured data from experimental work, then i interpolated and plot it with matplotlib contourplot. Now i want to validate my interpolation.
For this validation i need to know the plottet value from a specific (x,y) point out of my contourplot. Due to i want to check how close my interpolation at (x,y) to my messured data at (x,y) is.
At the end i want to plot the difference over x.
i hope you understand my problem and can help me!
thanks a lot!
import pandas as pd
import numpy as np
from matplotlib.pyplot import griddata
from matplotlib.pyplot import plot
df = pd.read_excel("my_work.xlsx")
x = df.loc["x_messured" ]
y = df.loc["y_messured" ]
z = df.loc["z_messured" ]
x_interp = np.linspace(0, max(x), 200)
y_interp = np.linspace(0, max(y), 200)
z2d = griddata((x, y), z, (x_interp[None,:], y_interp[:,None]))
matplotlib.pyplot.figure()
cs = plt.contour(x_interp, y_interp, z2d)
csf = plt.contourf(x_interp, y_interp, z2d, cmap="viridis")
diff = []
for q in range(len(x)):
diff.append( abs( z[q] - get_from_z2d(x[q], y[q]) ) )
plot(x, diff)
I need the function get_from_z2d()...

Scatter plot with scalar data

I want to create a scatter plot with matplotlib where the data points have scalar data attached to them and are assigned a color depending on how large their attached value is relative to the other points in the set. I.e., I want something akin to a heatmap. However, I'm looking for a "discrete" heatmap, i.e. nothing should be ploted where there were no points in the original data set and, in particular, no interpolation (in space) should be performed.
Can this be done?
you can use scatter, and set the attached value to c parameter:
import numpy as np
import pylab as pl
x = np.random.uniform(-1, 1, 1000)
y = np.random.uniform(-1, 1, 1000)
z = np.sqrt(x*x+y*y)
pl.scatter(x, y, c=z)
pl.colorbar()
pl.show()
Solving this in Altair.
import numpy as np
import pylab as pl
x = np.random.uniform(-1, 1, 1000)
y = np.random.uniform(-1, 1, 1000)
z = np.sqrt(x*x+y*y)
df = pd.DataFrame({'x':x,'y':y, 'z':z})
from altair import *
Chart(df).mark_circle().encode(x='x',y='y', color='z')