Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smoothed 2D histogram using matplotlib and imshow

I try to do a 2D histogram plot and to obtain a "smooth" picture by a sort of interpolation. Thus I do the following combining plt.hist2d and plt.imshow

import matplotlib.pyplot as plt
import numpy as np

data = np.loadtxt("parametre_optMC.dat", skiprows=50, usecols=(1,2))

h, x, y, p = plt.hist2d(data[:,0], data[:,1], bins = 20)
plt.imshow(h, origin = "lower", interpolation = "gaussian")
plt.savefig("test.pdf")

As you can see on the picture below, the two plots are superimposed and that is the problem for which I need some help

enter image description here

Adding clf works but I lose axes dimenions :

import matplotlib.pyplot as plt
import numpy as np

data = np.loadtxt("parametre_optMC.dat", skiprows=50, usecols=(1,2))

h, x, y, p = plt.hist2d(data[:,0], data[:,1], bins = 20)
plt.clf()
plt.imshow(h, origin = "lower", interpolation = "gaussian")
plt.savefig("test.pdf")

enter image description here

like image 535
Ger Avatar asked May 27 '14 09:05

Ger


2 Answers

Perhaps it would be better to plot a kernel density estimate?

import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

data = np.random.multivariate_normal([0, 0], [(1, .6), (.6, 1)], 100)
f, ax = plt.subplots(figsize=(7, 7))
sns.kdeplot(data, shade=True, ax=ax)

enter image description here

like image 182
mwaskom Avatar answered Nov 15 '22 17:11

mwaskom


To your first question:

You need to clear data from a previous plot, putting the following before you plot should do this:

plt.clf()
plt.close()

To your second question:

To change the axis values I'd suggest the extent parameter (see this answer).

e.g. something like:

plt.imshow(h, origin = "lower", interpolation = "gaussian",extent=[-100,100,-75,75])
like image 33
atomh33ls Avatar answered Nov 15 '22 18:11

atomh33ls