Note
Click here to download the full example code
04. 2D Contour & marginal histograms
This script demonstrates how to create a combined visualization using Plotly. It displays the relationship between two variables using a 2D density contour plot overlaid with a scatter plot of the individual data points. To show the distribution of each variable independently, marginal histograms are added to the top and right axes.
Note
Example from Plotly: https://plotly.com/python/2d-histogram-contour/
15 import numpy as np
16 import plotly.graph_objects as go
17
18 from plotly.io import show
19
20 try:
21 __file__
22 TERMINAL = True
23 except:
24 TERMINAL = False
25
26 # ----------------
27 # Create data
28 # ----------------
29 t = np.linspace(-1, 1.2, 2000)
30 x = (t**3) + (0.3 * np.random.randn(2000))
31 y = (t**6) + (0.3 * np.random.randn(2000))
32
33 # ----------------
34 # Create figure
35 # ----------------
36 fig = go.Figure()
37 fig.add_trace(go.Histogram2dContour(
38 x = x,
39 y = y,
40 colorscale = 'Blues', # 'Jet'
41 contours = dict(
42 showlabels = True,
43 labelfont = dict(
44 family = 'Raleway',
45 color ='white'
46 )
47 ),
48 hoverlabel = dict(
49 bgcolor = 'white',
50 bordercolor = 'black',
51 font = dict(
52 family = 'Raleway',
53 color = 'black'
54 )
55 ),
56 reversescale = True,
57 xaxis = 'x',
58 yaxis = 'y'
59 ))
60 fig.add_trace(go.Scatter(
61 x = x,
62 y = y,
63 xaxis = 'x',
64 yaxis = 'y',
65 mode = 'markers',
66 marker = dict(
67 color = 'rgba(0,0,0,0.3)',
68 size = 3
69 )
70 ))
71 fig.add_trace(go.Histogram(
72 y = y,
73 xaxis = 'x2',
74 marker = dict(
75 color = 'rgba(0,0,0,1)'
76 )
77 ))
78 fig.add_trace(go.Histogram(
79 x = x,
80 yaxis = 'y2',
81 marker = dict(
82 color = 'rgba(0,0,0,1)'
83 )
84 ))
85
86 fig.update_layout(
87 autosize = False,
88 xaxis = dict(
89 zeroline = False,
90 domain = [0,0.85],
91 showgrid = False
92 ),
93 yaxis = dict(
94 zeroline = False,
95 domain = [0,0.85],
96 showgrid = False
97 ),
98 xaxis2 = dict(
99 zeroline = False,
100 domain = [0.85,1],
101 showgrid = False
102 ),
103 yaxis2 = dict(
104 zeroline = False,
105 domain = [0.85,1],
106 showgrid = False
107 ),
108 height = 600,
109 width = 600,
110 bargap = 0,
111 hovermode = 'closest',
112 showlegend = False
113 )
114
115 # Show
116 show(fig)
Total running time of the script: ( 0 minutes 1.931 seconds)