At the top, import
from scipy.ndimage.filters
import gaussian_filter
Then use it like this:
df3_smooth = gaussian_filter(df3, sigma = 1)
sns.heatmap(df3_smooth, vmin = -40, vmax = 150, cmap = "coolwarm", cbar = True, cbar_kws = {
"ticks": [-40, 150, -20, 0, 25, 50, 75, 100, 125]
})
Keep in mind that that will also "smooth out" any maximum data peaks you have, so your minimum and maximum data will not be the same that you specified in your normalization anymore. To still get good looking heatmaps I would suggest not using fixed values for your vmin
and vmax
, but:
sns.heatmap(df3_smooth, vmin = np.min(df3_smooth), vmax = np.max(df3_smooth), cmap = "coolwarm", cbar = True, cbar_kws = {
"ticks": [-40, 150, -20, 0, 25, 50, 75, 100, 125]
})
This is an Axes-level function and will draw the heatmap into the currently-active Axes if none is provided to the ax argument. Part of this Axes space will be taken and used to plot a colormap, unless cbar is False or a separate Axes is provided to cbar_ax.,Plot rectangular data as a color-encoded matrix.,The value at which to center the colormap when plotting divergant data. Using this parameter will change the default cmap if none is specified.,Axes in which to draw the plot, otherwise use the currently-active Axes.
>>>
import numpy as np;
np.random.seed(0) >>>
import seaborn as sns;
sns.set_theme() >>>
uniform_data = np.random.rand(10, 12) >>>
ax = sns.heatmap(uniform_data)
>>> ax = sns.heatmap(uniform_data, vmin = 0, vmax = 1)
>>> normal_data = np.random.randn(10, 12) >>> ax = sns.heatmap(normal_data, center = 0)
>>> flights = sns.load_dataset("flights") >>>
flights = flights.pivot("month", "year", "passengers") >>>
ax = sns.heatmap(flights)
>>> ax = sns.heatmap(flights, annot = True, fmt = "d")
>>> ax = sns.heatmap(flights, linewidths = .5)
While this stateful interface is fast and convenient for simple plots, it is easy to run into problems. For example, once the second panel is created, how can we go back and add something to the first? This is possible within the MATLAB-style interface, but a bit clunky. Fortunately, there is a better way.,Apparently the people with fast splits are the elite runners who are finishing within ~15,000 seconds, or about 4 hours. People slower than that are much less likely to have a fast second split.,An answer to these problems is Seaborn. Seaborn provides an API on top of Matplotlib that offers sane choices for plot style and color defaults, defines simple high-level functions for common statistical plot types, and integrates with the functionality provided by Pandas DataFrames.,The plt.FuncFormatter() offers extremely fine-grained control over the appearance of your plot ticks, and comes in very handy when you’re preparing plots for presentation or publication.
So, for example, you may have a file called myplot.py containing the following:
#-- -- -- - file: myplot.py-- -- --
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10, 100)
plt.plot(x, np.sin(x))
plt.plot(x, np.cos(x))
plt.show()
You can then run this script from the command-line prompt, which will result in a window opening with your figure displayed:
$ python myplot.py
It can be very convenient to use Matplotlib interactively within an
IPython shell (see
Chapter 1). IPython is built to work well with Matplotlib if you specify
Matplotlib mode. To enable this mode, you can use the %matplotlib
magic command after starting ipython
:
In[1]: % matplotlib
Using matplotlib backend: TkAgg
In[2]: import matplotlib.pyplot as plt
For this book, we will generally opt for %matplotlib inline
:
In[3]: % matplotlib inline
After you run this command (it needs to be done only once per kernel/session), any cell within the notebook that creates a plot will embed a PNG image of the resulting graphic (Figure 4-1):
In[4]: import numpy as np
x = np.linspace(0, 10, 100)
fig = plt.figure()
plt.plot(x, np.sin(x), '-')
plt.plot(x, np.cos(x), '--');
One nice feature of Matplotlib is the ability to save figures in a wide
variety of formats. You can save a figure using the savefig()
command. For example, to save the previous figure as a PNG file, you can
run this:
In[5]: fig.savefig('my_figure.png')
We now have a file called my_figure.png in the current working directory:
In[6]: !ls - lh my_figure.png
In
[
6
]:
!
ls
-
lh
my_figure
.
png
-rw - r--r--1 jakevdp staff 16 K Aug 11 10: 59 my_figure.png
In savefig()
, the file format is inferred from the extension of the
given filename. Depending on what backends you have installed, many
different file formats are available. You can find the list of supported file types for your system by using the following method of the figure
canvas
object:
In[8]: fig.canvas.get_supported_filetypes()
In
[
8
]:
fig
.
canvas
.
get_supported_filetypes
()
Out[8]: {
'eps': 'Encapsulated Postscript',
'jpeg': 'Joint Photographic Experts Group',
'jpg': 'Joint Photographic Experts Group',
'pdf': 'Portable Document Format',
'pgf': 'PGF code for LaTeX',
'png': 'Portable Network Graphics',
'ps': 'Postscript',
'raw': 'Raw RGBA bitmap',
'rgba': 'Raw RGBA bitmap',
'svg': 'Scalable Vector Graphics',
'svgz': 'Scalable Vector Graphics',
'tif': 'Tagged Image File Format',
'tiff': 'Tagged Image File Format'
}
One potential issue with this plot is that it is a bit "splotchy." That is, the color steps are discrete rather than continuous, which is not always what is desired. This could be remedied by setting the number of contours to a very high number, but this results in a rather inefficient plot: Matplotlib must render a new polygon for each step in the level. A better way to handle this is to use the plt.imshow() function, which interprets a two-dimensional grid of data as an image.,Our plot is looking nicer, but the spaces between the lines may be a bit distracting. We can change this by switching to a filled contour plot using the plt.contourf() function (notice the f at the end), which uses largely the same syntax as plt.contour().,plt.imshow() by default follows the standard image array definition where the origin is in the upper left, not in the lower left as in most contour plots. This must be changed when showing gridded data., The text is released under the CC-BY-NC-ND license, and code is released under the MIT license. If you find this content useful, please consider supporting the work by buying the book!
% matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import numpy as np
def f(x, y):
return np.sin(x) ** 10 + np.cos(10 + y * x) * np.cos(x)
x = np.linspace(0, 5, 50) y = np.linspace(0, 5, 40) X, Y = np.meshgrid(x, y) Z = f(X, Y)
plt.contour(X, Y, Z, colors = 'black');
plt.contour(X, Y, Z, 20, cmap = 'RdGy');
Here we chose the RdGy
(short for Red-Gray) colormap, which is a good choice for centered data.
Matplotlib has a wide range of colormaps available, which you can easily browse in IPython by doing a tab completion on the plt.cm
module:
plt.cm.<TAB>
If you do not specify x and y coordinates, integer indices are used for the x and y axis. You can also pass x and y values to go.Surface.,You can use the surfacecolor attribute to define the color of the surface of your figure. In this example, the surface color represents the distance from the origin, rather than the default, which is the z value.,Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.,Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.
import plotly.graph_objects as go import pandas as pd # Read data from a csv z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv') fig = go.Figure(data = [go.Surface(z = z_data.values)]) fig.update_layout(title = 'Mt Bruno Elevation', autosize = False, width = 500, height = 500, margin = dict(l = 65, r = 50, b = 65, t = 90)) fig.show()
import plotly.graph_objects as go import pandas as pd import numpy as np # Read data from a csv z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv') z = z_data.values sh_0, sh_1 = z.shape x, y = np.linspace(0, 1, sh_0), np.linspace(0, 1, sh_1) fig = go.Figure(data = [go.Surface(z = z, x = x, y = y)]) fig.update_layout(title = 'Mt Bruno Elevation', autosize = False, width = 500, height = 500, margin = dict(l = 65, r = 50, b = 65, t = 90)) fig.show()
import plotly.graph_objects as go import pandas as pd # Read data from a csv z_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/api_docs/mt_bruno_elevation.csv') fig = go.Figure(data = [go.Surface(z = z_data.values)]) fig.update_traces(contours_z = dict(show = True, usecolormap = True, highlightcolor = "limegreen", project_z = True)) fig.update_layout(title = 'Mt Bruno Elevation', autosize = False, scene_camera_eye = dict(x = 1.87, y = 0.88, z = -0.64), width = 500, height = 500, margin = dict(l = 65, r = 50, b = 65, t = 90) ) fig.show()
import plotly.graph_objects as go
fig = go.Figure(go.Surface(
contours = {
"x": {
"show": True,
"start": 1.5,
"end": 2,
"size": 0.04,
"color": "white"
},
"z": {
"show": True,
"start": 0.5,
"end": 0.8,
"size": 0.05
}
},
x = [1, 2, 3, 4, 5],
y = [1, 2, 3, 4, 5],
z = [
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0]
]))
fig.update_layout(
scene = {
"xaxis": {
"nticks": 20
},
"zaxis": {
"nticks": 4
},
'camera_eye': {
"x": 0,
"y": -1,
"z": 0.5
},
"aspectratio": {
"x": 1,
"y": 1,
"z": 0.2
}
})
fig.show()
import plotly.graph_objects as go
import numpy as np
z1 = np.array([
[8.83, 8.89, 8.81, 8.87, 8.9, 8.87],
[8.89, 8.94, 8.85, 8.94, 8.96, 8.92],
[8.84, 8.9, 8.82, 8.92, 8.93, 8.91],
[8.79, 8.85, 8.79, 8.9, 8.94, 8.92],
[8.79, 8.88, 8.81, 8.9, 8.95, 8.92],
[8.8, 8.82, 8.78, 8.91, 8.94, 8.92],
[8.75, 8.78, 8.77, 8.91, 8.95, 8.92],
[8.8, 8.8, 8.77, 8.91, 8.95, 8.94],
[8.74, 8.81, 8.76, 8.93, 8.98, 8.99],
[8.89, 8.99, 8.92, 9.1, 9.13, 9.11],
[8.97, 8.97, 8.91, 9.09, 9.11, 9.11],
[9.04, 9.08, 9.05, 9.25, 9.28, 9.27],
[9, 9.01, 9, 9.2, 9.23, 9.2],
[8.99, 8.99, 8.98, 9.18, 9.2, 9.19],
[8.93, 8.97, 8.97, 9.18, 9.2, 9.18]
])
z2 = z1 + 1
z3 = z1 - 1
fig = go.Figure(data = [
go.Surface(z = z1),
go.Surface(z = z2, showscale = False, opacity = 0.9),
go.Surface(z = z3, showscale = False, opacity = 0.9)
])
fig.show()
import plotly.graph_objects as go from plotly.subplots import make_subplots # Equation of ring cyclide # see https: //en.wikipedia.org/wiki/Dupin_cyclide import numpy as np a, b, d = 1.32, 1., 0.8 c = a ** 2 - b ** 2 u, v = np.mgrid[0: 2 * np.pi: 100 j, 0: 2 * np.pi: 100 j] x = (d * (c - a * np.cos(u) * np.cos(v)) + b ** 2 * np.cos(u)) / (a - c * np.cos(u) * np.cos(v)) y = b * np.sin(u) * (a - d * np.cos(v)) / (a - c * np.cos(u) * np.cos(v)) z = b * np.sin(v) * (c * np.cos(u) - d) / (a - c * np.cos(u) * np.cos(v)) fig = make_subplots(rows = 1, cols = 2, specs = [ [{ 'is_3d': True }, { 'is_3d': True }] ], subplot_titles = ['Color corresponds to z', 'Color corresponds to distance to origin'], ) fig.add_trace(go.Surface(x = x, y = y, z = z, colorbar_x = -0.07), 1, 1) fig.add_trace(go.Surface(x = x, y = y, z = z, surfacecolor = x ** 2 + y ** 2 + z ** 2), 1, 2) fig.update_layout(title_text = "Ring cyclide") fig.show()