DV 9
DV 9
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.
• 3D Line Plot: Creates a 3D line plot where lines connect points specified by x, y, and
z coordinates.
• 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 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")
----------------------------------------------------------------------
-----
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.
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,
import pandas as pd
import plotly.express as px
# Create a DataFrame
df = pd.DataFrame(data)
print(df)
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()
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 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
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.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
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
----------------------------------------------------------------------
-----
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.