0% found this document useful (0 votes)
44 views11 pages

DV 9

The document discusses creating 3D plots in Python using Plotly libraries. It describes several 3D plot types including line, surface, and scatter plots. Code examples are provided to generate 3D plots from sample data using Plotly Express.

Uploaded by

Anish Nayak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views11 pages

DV 9

The document discusses creating 3D plots in Python using Plotly libraries. It describes several 3D plot types including line, surface, and scatter plots. Code examples are provided to generate 3D plots from sample data using Plotly Express.

Uploaded by

Anish Nayak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1. Write a Python program to draw 3D Plots using Plotly Libraries.

Plotly is a collection of open-source libraries for creating interactive data visualizations in


Python, R, and JavaScript. It offers a variety of tools and APIs for building dashboards, web
applications, and scientific computing interfaces.

plotly.express is a high-level interface for creating interactive plots and visualizations in Python
using the Plotly library. It provides a simple and intuitive syntax for generating a wide range of
plot types with minimal code. The read_csv() function in pandas is used to read data from a CSV
(Comma Separated Values) file into a DataFrame, which is a tabular data structure in pandas.

Plotly Express offers several 3D plots

• 3D Line Plot: Creates a 3D line plot where lines connect points specified by x, y, and
z coordinates.

• 3D Surface Plot: Creates a 3D surface plot from a 2D grid of x, y, and z values,


representing a surface in three-dimensional space.

• 3D Mesh Plot: Creates a 3D mesh plot from a set of vertices and a connectivity
matrix, representing a mesh or wireframe in three-dimensional space.

• 3D Contour Plot: Creates a 3D contour plot from a set of x, y, and z coordinates,


representing contours of constant values in three-dimensional space.

• 3D Cone Plot: Creates a 3D cone plot where each cone represents a data point
specified by x, y, and z coordinates, with optional size, color, and orientation.

• 3D Scatter Polar Plot: Creates a 3D scatter polar plot where each point is
represented by its polar coordinates (azimuth, elevation, and distance) in three-
dimensional space.

import pandas as pd
from holoviews import opts
import hvplot.scatter

df = pd.read_csv("Countries Population.csv")

# Remove commas and convert 'Population -2023' to numeric


df['Population -2023'] = pd.to_numeric(df['Population -
2023'].str.replace(',', ''))
print(df)
# Plotting with hvplot.scatter
scatter = df.hvplot.scatter(x='World Share', y='Country (or
dependency)',
size='Population -2023', color='blue',
width=800, height=500)

scatter.opts(opts.Scatter(tools=['hover'], color='blue', size=5))


----------------------------------------------------------------------
-----
ModuleNotFoundError Traceback (most recent call
last)
<ipython-input-2-447c37959cca> in <cell line: 3>()
1 import pandas as pd
2 from holoviews import opts
----> 3 import hvplot.scatter
4
5 df = pd.read_csv("Countries Population.csv")

ModuleNotFoundError: No module named 'hvplot'

----------------------------------------------------------------------
-----
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the


"Open Examples" button below.
----------------------------------------------------------------------
-----

#3D Scatter plot using plotly


import pandas as pd
import plotly.express as px

csv_file='book.csv'

df=pd.read_csv(csv_file)
print(df)
fig=px.scatter_3d(df,
x='Size',
y='InLibrary',
z='Price',
color='Price',
color_continuous_scale='viridis')
fig.show()

----------------------------------------------------------------------
-----
FileNotFoundError Traceback (most recent call
last)
<ipython-input-17-31924eafd9b0> in <cell line: 7>()
5 csv_file='book.csv'
6
----> 7 df=pd.read_csv(csv_file)
8 print(df)
9 fig=px.scatter_3d(df,
/usr/local/lib/python3.10/dist-packages/pandas/util/_decorators.py in
wrapper(*args, **kwargs)
209 else:
210 kwargs[new_arg_name] = new_arg_value
--> 211 return func(*args, **kwargs)
212
213 return cast(F, wrapper)

/usr/local/lib/python3.10/dist-packages/pandas/util/_decorators.py in
wrapper(*args, **kwargs)
329 stacklevel=find_stack_level(),
330 )
--> 331 return func(*args, **kwargs)
332
333 # error: "Callable[[VarArg(Any), KwArg(Any)], Any]"
has no

/usr/local/lib/python3.10/dist-packages/pandas/io/parsers/readers.py
in read_csv(filepath_or_buffer, sep, delimiter, header, names,
index_col, usecols, squeeze, prefix, mangle_dupe_cols, dtype, engine,
converters, true_values, false_values, skipinitialspace, skiprows,
skipfooter, nrows, na_values, keep_default_na, na_filter, verbose,
skip_blank_lines, parse_dates, infer_datetime_format, keep_date_col,
date_parser, dayfirst, cache_dates, iterator, chunksize, compression,
thousands, decimal, lineterminator, quotechar, quoting, doublequote,
escapechar, comment, encoding, encoding_errors, dialect,
error_bad_lines, warn_bad_lines, on_bad_lines, delim_whitespace,
low_memory, memory_map, float_precision, storage_options)
948 kwds.update(kwds_defaults)
949
--> 950 return _read(filepath_or_buffer, kwds)
951
952

/usr/local/lib/python3.10/dist-packages/pandas/io/parsers/readers.py
in _read(filepath_or_buffer, kwds)
603
604 # Create the parser.
--> 605 parser = TextFileReader(filepath_or_buffer, **kwds)
606
607 if chunksize or iterator:

/usr/local/lib/python3.10/dist-packages/pandas/io/parsers/readers.py
in __init__(self, f, engine, **kwds)
1440
1441 self.handles: IOHandles | None = None
-> 1442 self._engine = self._make_engine(f, self.engine)
1443
1444 def close(self) -> None:
/usr/local/lib/python3.10/dist-packages/pandas/io/parsers/readers.py
in _make_engine(self, f, engine)
1733 if "b" not in mode:
1734 mode += "b"
-> 1735 self.handles = get_handle(
1736 f,
1737 mode,

/usr/local/lib/python3.10/dist-packages/pandas/io/common.py in
get_handle(path_or_buf, mode, encoding, compression, memory_map,
is_text, errors, storage_options)
854 if ioargs.encoding and "b" not in ioargs.mode:
855 # Encoding
--> 856 handle = open(
857 handle,
858 ioargs.mode,

FileNotFoundError: [Errno 2] No such file or directory: 'book.csv'

import pandas as pd
import plotly.express as px

# Define the data


data = {
'Citations': ['Some', 'Many', 'Many', 'Many'],
'Size': ['Small', 'Big', 'Medium', 'Small'],
'InLibrary': ['No', 'No', 'No', 'No'],
'Price': ['Affordable', 'Expensive', 'Expensive', 'Affordable'],
'Editions': ['One', 'Many', 'Few', 'Many'],
'label': ['No', 'Yes', 'Yes', 'Yes']
}#ISO 3166-1 alpha-3

# Create a DataFrame
df = pd.DataFrame(data)
print(df)

# Create 3D scatter plot


#fig = px.scatter_3d(df, x='Size', y='InLibrary', z='Price',
color='Price', size='Price', color_continuous_scale='viridis')
fig = px.scatter_3d(df, x='Size', y='InLibrary',
z='Price',color='Price',color_continuous_scale='viridis')

# Show the plot


fig.show()

Citations Size InLibrary Price Editions label


0 Some Small No Affordable One No
1 Many Big No Expensive Many Yes
2 Many Medium No Expensive Few Yes
3 Many Small No Affordable Many Yes

1. 3D Line Plot
import plotly.express as px
import numpy as np
x = np.linspace(0, 10, 100)
print(x)
y = np.sin(x)
z = np.cos(x)
fig = px.line_3d(x=x, y=y, z=z)
fig.show()

[ 0. 0.1010101 0.2020202 0.3030303 0.4040404


0.50505051
0.60606061 0.70707071 0.80808081 0.90909091 1.01010101
1.11111111
1.21212121 1.31313131 1.41414141 1.51515152 1.61616162
1.71717172
1.81818182 1.91919192 2.02020202 2.12121212 2.22222222
2.32323232
2.42424242 2.52525253 2.62626263 2.72727273 2.82828283
2.92929293
3.03030303 3.13131313 3.23232323 3.33333333 3.43434343
3.53535354
3.63636364 3.73737374 3.83838384 3.93939394 4.04040404
4.14141414
4.24242424 4.34343434 4.44444444 4.54545455 4.64646465
4.74747475
4.84848485 4.94949495 5.05050505 5.15151515 5.25252525
5.35353535
5.45454545 5.55555556 5.65656566 5.75757576 5.85858586
5.95959596
6.06060606 6.16161616 6.26262626 6.36363636 6.46464646
6.56565657
6.66666667 6.76767677 6.86868687 6.96969697 7.07070707
7.17171717
7.27272727 7.37373737 7.47474747 7.57575758 7.67676768
7.77777778
7.87878788 7.97979798 8.08080808 8.18181818 8.28282828
8.38383838
8.48484848 8.58585859 8.68686869 8.78787879 8.88888889
8.98989899
9.09090909 9.19191919 9.29292929 9.39393939 9.49494949
9.5959596
9.6969697 9.7979798 9.8989899 10. ]

1. 3D Surface Plot:
import plotly.graph_objects as go
import numpy as np
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
x, y = np.meshgrid(x, y)
z = np.sin(np.sqrt(x**2 + y**2))
fig = go.Figure(data=[go.Surface( x=x,z=z, y=y)])
fig.update_layout(
title='3D Surface Plot',
scene=dict(
xaxis_title='X-axis',
yaxis_title='Y-axis',
zaxis_title='Z-axis'))
fig.show()

import matplotlib.pyplot as plt


import numpy as numpy
x=['jan','feb','mar','apr']
y=[10,20,30,40]
plt.plot(x,y,marker='*',label='linear plot')
plt.xlabel('month')
plt.ylabel('sales')
plt.legend(loc='upper right')
plt.show()
1. 3D Mesh Plot:
Indented block

import plotly.graph_objects as go
import numpy as np
z = 15 * np.random.random(100)
x = np.sin(z) + 0.1 * np.random.randn(100)
y = np.cos(z) + 0.1 * np.random.randn(100)
fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='green',
opacity=1,alphahull=3)])
fig.show()

import plotly.graph_objects as go
import numpy as np

# Data for three-dimensional scattered points


z = 15 * np.random.random(100)
x = np.sin(z) + 0.1 * np.random.randn(100)
y = np.cos(z) + 0.1 * np.random.randn(100)

fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='green',


opacity=1, alphahull=3,
i=[1, 0, 0, 1],
j=[1, 2, 3, 4],
k=[4, 3, 1, 3],)])

fig.show()

1. 3D Contour Plot:
import plotly.graph_objects as go
import numpy as np
data = [[1,2,3,4,5],
[3,4,5,6,7],
[7,8,9,6,4],
[3,7,2,4,2]]
fig = go.Figure(data =
go.Contour(z = data))
fig.show()

1. 3D Cone Plot:
# Basic 3D Cone Plot
import plotly.graph_objects as go

fig = go.Figure(data=go.Cone(x=[1], y=[1], z=[1], u=[1], v=[1],


w=[0]))

fig.update_layout(scene_camera_eye=dict(x=-0.76, y=1.8, z=0.92))

fig.show()
#
import plotly.graph_objects as go

fig = go.Figure(data=go.Cone(
x=[1, 2, 3],
y=[1, 2, 3],
z=[1, 2, 3],
u=[1, 0, 0],
v=[0, 3, 0],
w=[0, 0, 2],
sizemode="absolute",
sizeref=2,
anchor="tip"))

fig.update_layout(
scene=dict(domain_x=[0, 1],
camera_eye=dict(x=-1.57, y=1.36, z=0.58)))

fig.show()

3D Scatter Plot

import plotly.express as px
df = px.data.iris()
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width',
z='petal_width',
color='petal_length', size='petal_length', size_max=18,
symbol='species', opacity=0.7)

# tight layout
fig.update_layout(margin=dict(l=0, r=0, b=0, t=0))
fig.show()

import plotly.graph_objects as go
import numpy as np

# Download data set from plotly repo


#
'https://raw.githubusercontent.com/plotly/datasets/master/mesh_dataset
.txt'))
pts =
np.loadtxt(np.DataSource().open('https://raw.githubusercontent.com/
plotly/datasets/master/mesh_dataset.txt'))
x, y, z = pts.T

fig = go.Figure(data=[go.Mesh3d(x=x, y=y, z=z, color='lightpink',


opacity=0.50)])
fig.show()

pip install dash


Collecting dash
Downloading dash-2.15.0-py3-none-any.whl (10.2 MB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 10.2/10.2 MB 19.4 MB/s eta
0:00:00
ent already satisfied: Flask<3.1,>=1.0.4 in
/usr/local/lib/python3.10/dist-packages (from dash) (2.2.5)
Requirement already satisfied: Werkzeug<3.1 in
/usr/local/lib/python3.10/dist-packages (from dash) (3.0.1)
Requirement already satisfied: plotly>=5.0.0 in
/usr/local/lib/python3.10/dist-packages (from dash) (5.15.0)
Collecting dash-html-components==2.0.0 (from dash)
Downloading dash_html_components-2.0.0-py3-none-any.whl (4.1 kB)
Collecting dash-core-components==2.0.0 (from dash)
Downloading dash_core_components-2.0.0-py3-none-any.whl (3.8 kB)
Collecting dash-table==5.0.0 (from dash)
Downloading dash_table-5.0.0-py3-none-any.whl (3.9 kB)
Requirement already satisfied: typing-extensions>=4.1.1 in
/usr/local/lib/python3.10/dist-packages (from dash) (4.10.0)
Requirement already satisfied: requests in
/usr/local/lib/python3.10/dist-packages (from dash) (2.31.0)
Collecting retrying (from dash)
Downloading retrying-1.3.4-py3-none-any.whl (11 kB)
Requirement already satisfied: nest-asyncio in
/usr/local/lib/python3.10/dist-packages (from dash) (1.6.0)
Requirement already satisfied: setuptools in
/usr/local/lib/python3.10/dist-packages (from dash) (67.7.2)
Requirement already satisfied: importlib-metadata in
/usr/local/lib/python3.10/dist-packages (from dash) (7.0.1)
Requirement already satisfied: Jinja2>=3.0 in
/usr/local/lib/python3.10/dist-packages (from Flask<3.1,>=1.0.4->dash)
(3.1.3)
Requirement already satisfied: itsdangerous>=2.0 in
/usr/local/lib/python3.10/dist-packages (from Flask<3.1,>=1.0.4->dash)
(2.1.2)
Requirement already satisfied: click>=8.0 in
/usr/local/lib/python3.10/dist-packages (from Flask<3.1,>=1.0.4->dash)
(8.1.7)
Requirement already satisfied: tenacity>=6.2.0 in
/usr/local/lib/python3.10/dist-packages (from plotly>=5.0.0->dash)
(8.2.3)
Requirement already satisfied: packaging in
/usr/local/lib/python3.10/dist-packages (from plotly>=5.0.0->dash)
(23.2)
Requirement already satisfied: MarkupSafe>=2.1.1 in
/usr/local/lib/python3.10/dist-packages (from Werkzeug<3.1->dash)
(2.1.5)
Requirement already satisfied: zipp>=0.5 in
/usr/local/lib/python3.10/dist-packages (from importlib-metadata-
>dash) (3.17.0)
Requirement already satisfied: charset-normalizer<4,>=2 in
/usr/local/lib/python3.10/dist-packages (from requests->dash) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in
/usr/local/lib/python3.10/dist-packages (from requests->dash) (3.6)
Requirement already satisfied: urllib3<3,>=1.21.1 in
/usr/local/lib/python3.10/dist-packages (from requests->dash) (2.0.7)
Requirement already satisfied: certifi>=2017.4.17 in
/usr/local/lib/python3.10/dist-packages (from requests->dash)
(2024.2.2)
Requirement already satisfied: six>=1.7.0 in
/usr/local/lib/python3.10/dist-packages (from retrying->dash) (1.16.0)
Installing collected packages: dash-table, dash-html-components, dash-
core-components, retrying, dash
Successfully installed dash-2.15.0 dash-core-components-2.0.0 dash-
html-components-2.0.0 dash-table-5.0.0 retrying-1.3.4

from dash import Dash, dcc, html, Input, Output


import plotly.graph_objects as go
import pandas as pd

base_url =
"https://raw.githubusercontent.com/plotly/datasets/master/ply/"
mesh_names = ['sandal', 'scissors', 'shark', 'walkman']
dataframes = {
name: pd.read_csv(base_url + name + '-ply.csv')
for name in mesh_names
}

app = Dash(__name__)

app.layout = html.Div([
html.H4('PLY Object Explorer'),
html.P("Choose an object:"),
dcc.Dropdown(
id='dropdown',
options=mesh_names,
value="sandal",
clearable=False
),
dcc.Graph(id="graph"),
])

@app.callback(
Output("graph", "figure"),
Input("dropdown", "value"))
def display_mesh(name):
df = dataframes[name]
fig = go.Figure(go.Mesh3d(
x=df.x, y=df.y, z=df.z,
i=df.i, j=df.j, k=df.k,
facecolor=df.facecolor))
return fig

app.run_server(debug=True)

----------------------------------------------------------------------
-----
ModuleNotFoundError Traceback (most recent call
last)
<ipython-input-1-c6dee85897b9> in <cell line: 1>()
----> 1 from dash import Dash, dcc, html, Input, Output
2 import plotly.graph_objects as go
3 import pandas as pd
4
5

ModuleNotFoundError: No module named 'dash'

----------------------------------------------------------------------
-----
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the


"Open Examples" button below.
----------------------------------------------------------------------
-----

You might also like