2D density plot using pandas and seaborn - pandas

I'm trying to plot a heatmap like:
(https://seaborn.pydata.org/generated/seaborn.kdeplot.html - last plot on the page)
But when I try this with my code I get:
My Pandas dataframe exists of two cols (x and y - both int64) and a number of rows. :
My code:
sns.kdeplot(data=dataFrame, fill=True, thresh=0, levels=100, cmap="mako", cbar=True)
My question is now how do I get rid of the contours, fill the background an make a smooth colorbar on the side?

Related

Second Matplotlib figure doesn't save to file

I've drawn a plot that looks something like the following:
It was created using the following code:
import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
# 1. Plot a figure consisting of 3 separate axes
# ==============================================
plotNames = ['Plot1','Plot2','Plot3']
figure, axisList = plt.subplots(len(plotNames), sharex=True, sharey=True)
tempDF = pd.DataFrame()
tempDF['date'] = pd.date_range('2015-01-01','2015-12-31',freq='D')
tempDF['value'] = np.random.randn(tempDF['date'].size)
tempDF['value2'] = np.random.randn(tempDF['date'].size)
for i in range(len(plotNames)):
axisList[i].plot_date(tempDF['date'],tempDF['value'],'b-',xdate=True)
# 2. Create a new single axis in the figure. This new axis sits over
# the top of the axes drawn previously. Make all the components of
# the new single axis invisibe except for the x and y labels.
big_ax = figure.add_subplot(111)
big_ax.set_axis_bgcolor('none')
big_ax.set_xlabel('Date',fontweight='bold')
big_ax.set_ylabel('Random normal',fontweight='bold')
big_ax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')
big_ax.spines['right'].set_visible(False)
big_ax.spines['top'].set_visible(False)
big_ax.spines['left'].set_visible(False)
big_ax.spines['bottom'].set_visible(False)
# 3. Plot a separate figure
# =========================
figure2,ax2 = plt.subplots()
ax2.plot_date(tempDF['date'],tempDF['value2'],'-',xdate=True,color='green')
ax2.set_xlabel('Date',fontweight='bold')
ax2.set_ylabel('Random normal',fontweight='bold')
# Save plot
# =========
plt.savefig('tempPlot.png',dpi=300)
Basically, the rationale for plotting the whole picture is as follows:
Create the first figure and plot 3 separate axes using a loop
Plot a single axis in the same figure to sit on top of the graphs
drawn previously. Label the x and y axes. Make all other aspects of
this axis invisible.
Create a second figure and plot data on a single axis.
The plot displays just as I want when using jupyter-notebook but when the plot is saved, the file contains only the second figure.
I was under the impression that plots could have multiple figures and that figures could have multiple axes. However, I suspect I have a fundamental misunderstanding of the differences between plots, subplots, figures and axes. Can someone please explain what I'm doing wrong and explain how to get the whole image to save to a single file.
Matplotlib does not have "plots". In that sense,
plots are figures
subplots are axes
During runtime of a script you can have as many figures as you wish. Calling plt.save() will save the currently active figure, i.e. the figure you would get by calling plt.gcf().
You can save any other figure either by providing a figure number num:
plt.figure(num)
plt.savefig("output.png")
or by having a refence to the figure object fig1
fig1.savefig("output.png")
In order to save several figures into one file, one could go the way detailed here: Python saving multiple figures into one PDF file.
Another option would be not to create several figures, but a single one, using subplots,
fig = plt.figure()
ax = plt.add_subplot(611)
ax2 = plt.add_subplot(612)
ax3 = plt.add_subplot(613)
ax4 = plt.add_subplot(212)
and then plot the respective graphs to those axes using
ax.plot(x,y)
or in the case of a pandas dataframe df
df.plot(x="column1", y="column2", ax=ax)
This second option can of course be generalized to arbitrary axes positions using subplots on grids. This is detailed in the matplotlib user's guide Customizing Location of Subplot Using GridSpec
Furthermore, it is possible to position an axes (a subplot so to speak) at any position in the figure using fig.add_axes([left, bottom, width, height]) (where left, bottom, width, height are in figure coordinates, ranging from 0 to 1).

pyplot color chart of 2d function domain

How can I make a 2-d color plot of the domain of a function across two dimensions? Something like this:
def f(x):
return x[0]**2+6*x[1]**2+x[0]*x[1]+np.sin(x[0])+3*x[0]
x = np.arange(-5,5,0.1)
y = np.arange(-5,5,0.1)
plt.contours(x,y,f([x,y])
Change your last line to
plt.contour(f(np.meshgrid(x,y)))
That will evaluate f across a meshed grid of x and y and plot contours of that function. The tutorial on producing contour plots in matplotlib is here. In general, the tutorials there are pretty good and you can often find what you want.
If you want the axes labelled with the ranges in your x and y ranges - you need
plt.contour(x,y,f(np.meshgrid(x,y)))
You could instead do plt.pcolormesh(f(np.meshgrid(x,y))) if you prefer a 'heatmap' style to a contour plot.
For fun, I expanded the range and amplified the sin component in your function and produced a contour map and a heatmap (see output)
import matplotlib.pyplot as plt
import numpy as np
def f(x):
return x[0]**2+6*x[1]**2+x[0]*x[1]+150*np.sin(x[0])+3*x[0]
x = np.arange(-50,50,0.1)
y = np.arange(-50,50,0.1)
plt.contour(x,y,f(np.meshgrid(x,y)))
plt.show()
Contour output
pcolormesh output

Stacking multiple plots together with a single x-axis

Suppose I have multiple time dependent variables and I want to plot them all together stacked one of on top of another like the image below, how would I do so in matplotlib? Currently when I try plotting them they appear as multiple independent plots.
EDIT:
I have a Pandas dataframe with K columns corresponding to dependent variables and N rows corresponding to observed values for those K variables.
Sample code:
df = get_representation(mat) #df is the Pandas dataframe
for i in xrange(len(df.columns)):
plt.plot(df.ix[:,i])
plt.show()
I would like to plot them all one on top of another.
You could just stack all the curves by shifting each curve vertically:
df = get_representation(mat) #df is the Pandas dataframe
for i in xrange(len(df.columns)):
plt.plot(df.ix[:, i] + shift*i)
plt.show()
Here shift denotes the average distance between the curves.

Change colour of curve according to its y-value in matplotlib [duplicate]

This question already has answers here:
Having line color vary with data index for line graph in matplotlib?
(4 answers)
Set line colors according to colormap
(1 answer)
Closed 8 years ago.
I'm trying to replicate the style of the attached figure using matplotlib's facilities.
Basically, I want to change the colour of the curve according to its y-value using matplotlib.
The plot you've shown doesn't have the color set by the vertical axis of the plot (which is what I would consider the y-value). Instead, it just has 8 different plots overlain, each with a different color, without stating what the color means.
Here's an example of something that looks like your plot:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
# some fake data:
x = np.linspace(0, 2*np.pi, 1000)
fs = np.arange(1, 5.)
ys = np.sin(x*fs[:, None])
for y, f in zip(ys, fs):
plt.plot(x, y, lw=3, c=cm.hot(f/5))
If you actually want the color of one line to change with respect to its value, you have to kind of hack it, because any given Line2D object can only have one color, as far as I know. One way to do this is to make a scatter plot, where each dot can have any color.
x = np.linspace(0, 2*np.pi, 1000)
y = np.sin(2*x)
plt.scatter(x,y, c=cm.hot(np.abs(y)), edgecolor='none')
Notes:
The color vector should range between 0 and 1, so if y.max() > 1, then normalize by it: c=cm.hot(y/y.max()) and make sure it's all positive.
I used edgecolor='none' because by default the scatter markers have a black outline which makes the it look less like a uniform line.
If your data is spaced too far, you'll have to interpolate the data if you don't want gaps between markers.

Is it possible to display 2D array as polar plot using Matplotlib imshow()?

I'm new to matplotlib (and am loving it!), but am getting frustrated. I have a polar grid represented as a a 2D array. (rows are radial sections, columns are azimuthal sections)
I've been able to display the 2D array as both a rectangular image (R vs. theta) using pyplot.imshow() and as a polar plot using pyplot.pcolor(). However, pcolor() is painfully slow for the size of the arrays I'm using, so I want to be able to display the array as a polar grid using imshow().
Using pcolor(), this is as simple as setting polar=True for the subplot. Is there any way to display the 2D array as a polar plot using imshow()? without having to do coordinate transformations on the entire array?
Thanks in advance
After some research I discovered the pcolormesh() function, which has proven to be significantly faster than using pcolor() and comparable to the speed of imshow().
Here is my solution:
import matplotlib.pyplot as plt
import numpy as np
#...some data processing
theta,rad = np.meshgrid(used_theta, used_rad) #rectangular plot of polar data
X = theta
Y = rad
fig = plt.figure()
ax = fig.add_subplot(111)
ax.pcolormesh(X, Y, data2D) #X,Y & data2D must all be same dimensions
plt.show()