Plotly库是一个交互式开源库。这对于数据可视化和简单轻松地理解数据是非常有用的工具。plotly图形对象是plotly的高级接口,易于使用。它可以绘制各种类型的图形和图表,如散点图,折线图,条形图,箱形图,直方图,饼图等。
使用plotly库的优势:
- Plotly具有悬停工具功能,使我们能够检测大量数据点中的任何离群值或异常。
- 它在视觉上具有吸引力,可以被广泛的受众所接受。
- 它允许我们对图表进行无休止的自定义,使我们的图表对其他人更有意义和更容易理解。
安装
pip install plotly
快速开始
- 散点图:表示两个不同数值变量的值。它们主要用于表示两个变量之间的关系。
# import all required libraries
import numpy as np
import plotly
import plotly.graph_objects as go
import plotly.offline as pyo
from plotly.offline import init_notebook_modeinit_notebook_mode(connected=True)# generating 150 random integers
# from 1 to 50
x = np.random.randint(low=1, high=50, size=150)*0.1# generating 150 random integers
# from 1 to 50
y = np.random.randint(low=1, high=50, size=150)*0.1# plotting scatter plot
fig = go.Figure(data=go.Scatter(x=x, y=y, mode='markers'))fig.show()
- 条形图:用于比较不同的数据组,推断哪些组最高,哪些组最常见,并比较一组与其他组相比的表现。
# import all required libraries
import numpy as np
import plotly
import plotly.graph_objects as go
import plotly.offline as pyo
from plotly.offline import init_notebook_modeinit_notebook_mode(connected = True)# countries on x-axis
countries=['India', 'canada','Australia','Brazil','Mexico','Russia','Germany','Switzerland','Texas']# plotting corresponding y for each
# country in x
fig = go.Figure([go.Bar(x=countries,y=[80,70,60,50,40,50,60,70,80])])fig.show()
- 饼图:饼图表示不同变量在总体中的分布。在饼图中,每个切片显示了其对总量的贡献。
import numpy as np
import plotly
import plotly.graph_objects as go
import plotly.offline as pyo
from plotly.offline import init_notebook_modeinit_notebook_mode(connected = True)# different individual parts in
# total chart
countries=['India', 'canada','Australia','Brazil','Mexico','Russia','Germany','Switzerland','Texas']# values corresponding to each
# individual country present in
# countries
values = [4500, 2500, 1053, 500,3200, 1500, 1253, 600, 3500]# plotting pie chart
fig = go.Figure(data=[go.Pie(labels=countries,values=values)])fig.show()
- 直方图:直方图将变量的连续分布绘制为一系列条形图,每个条形图表示变量中出现值的频率。为了使用直方图,我们只需要一个接受连续数值的变量。
# import all required libraries
import numpy as np
import plotly
import plotly.graph_objects as go
import plotly.offline as pyo
from plotly.offline import init_notebook_modeinit_notebook_mode(connected = True)# save the state of random
np.random.seed(42)# generating 250 random numbers
x = np.random.randn(250)# plotting histogram for x
fig = go.Figure(data=[go.Histogram(x=x)])fig.show()
- 箱形图:箱形图是统计总结的表示。最小值、第一四分位数、中位数、第三四分位数、最大值。
# import all required libraries
import numpy as np
import plotly
import plotly.graph_objects as go
import plotly.offline as pyo
from plotly.offline import init_notebook_modeinit_notebook_mode(connected = True)np.random.seed(42)# generating 50 random numbers
y = np.random.randn(50)# generating 50 random numbers
y1 = np.random.randn(50)
fig = go.Figure()# updating the figure with y
fig.add_trace(go.Box(y=y))# updating the figure with y1
fig.add_trace(go.Box(y=y1))fig.show()