Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Plotly绘图,快速入门

Plotly绘图,快速入门

原创
作者头像
皮大大
发布于 2024-06-29 09:46:22
发布于 2024-06-29 09:46:22
39402
代码可运行
举报
运行总次数:2
代码可运行

公众号:尤而小屋 编辑:Peter 作者:Peter

大家好,我是Peter~

本文基于一份公开的数据讲解plotly的多种图形的绘制,包含:

  • 散点图
  • 分组散点图
  • 气泡图
  • 3D散点图
  • 线形图
  • 柱状图
  • 分组柱状图
  • 堆叠柱状图
  • 箱型图
  • 饼图
  • 甜甜圈图
  • 直方图
  • 核密度图
  • 热力图
  • 子图

部分图预览:

1 plotly图形

Plotly是一个用于创建交互式图表的Python库,它支持多种图表类型,如折线图、散点图、饼图、热力图等。Plotly的特点如下:

  1. 高度可定制:用户可以根据需要调整图表的各种属性,如颜色、字体、轴标签等,以创建符合需求的可视化效果。
  2. 交互性:生成的图表具有交互性,用户可以通过鼠标悬停、拖动、缩放等操作查看数据详情和变化趋势。
  3. 跨平台:支持在Web、Jupyter Notebook、Python脚本等多种环境中使用,并且可以将图表导出为HTML、PNG、SVG等格式。
  4. 集成其他库:可以与其他流行的Python数据处理和可视化库(如Pandas、NumPy、Matplotlib等)结合使用,方便数据处理和图形绘制。
  5. 多语言支持:除了Python,Plotly还支持R、JavaScript、MATLAB等多种编程语言,方便不同背景的用户使用。

总之,Plotly是一个功能强大、易于使用的可视化库,适用于数据分析、科学计算、商业智能等领域。

2 导入库

In 1:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
import os
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
%matplotlib inline

from datetime import date, time, datetime
import plotly.graph_objs as go
import plotly.offline as pyo
import plotly.figure_factory as ff
import plotly.express as px
from plotly import tools
from plotly.subplots import make_subplots
from plotly.offline import iplot

import warnings
warnings.filterwarnings('ignore')

3 读取数据

In 2:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
df = pd.read_csv("StudentsPerformance.csv")
df.head()

4 散点图Scatter charts

In 3:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 基于px
fig = px.scatter(df,x="reading score",y="writing score")

fig.show()

另一种方式:

In 4:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 基于go.Scatter
scatter = [go.Scatter(x = df['reading score'],
                      y = df['writing score'],
                      mode ='markers')] 

fig = go.Figure(scatter)

# iplot(fig)
fig.show()

对散点进行自定义:

In 5:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 进阶版

data = [go.Scatter(x = df['reading score'],
                   y = df['writing score'],
                   mode = 'markers',
                   marker = dict(size = 12,
                                 color = 'rgb(0, 189, 255)',
                                 symbol = 'diamond',
                                 opacity = 0.75,
                                 line={'color': 'black',
                                       'width': 1.5}))]

layout = go.Layout(title=dict(text='Reading Score & Writing Score',
                              y=0.9,
                              x=0.5,
                              xanchor= 'center',
                              yanchor= 'top'),
                   xaxis={'title':'Reading Score'},
                   yaxis=dict(title = 'Writing Score'),
                   hovermode = 'closest',
                   template = 'plotly_white')

fig = go.Figure(data = data, layout = layout)
# iplot(fig)
fig.show()

5 分组散点图

In 6:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
trace_male = (go.Scatter(x=df[df['gender']=='male']['math score'],  # x-y轴数据
                         y = df[df['gender']=='male']['writing score'],
                         showlegend=True,  # 显示legend
                         text='Male', # 标题和名称
                         name='Male',
                         mode='markers',  # 符号标记类型
                         marker = dict(color= 'cornflowerblue',  # 符号属性的自定义:颜色、大小、透明度
                                       size = 9,
                                       opacity = 0.55)))

trace_female = (go.Scatter(x=df[df['gender'] == 'female']['math score'],
                           y = df[df['gender'] == 'female']['writing score'],
                           showlegend=True,
                           text='Female',
                           name = 'Female',
                           mode = 'markers',
                           marker = dict(color = 'darkorange',
                                         size = 9,
                                         opacity = 0.55)))
        
data=[trace_male,trace_female]  # 生成的数据

# 布局
layout= go.Layout(title = 'Math Score & Writing Score',
                  xaxis = dict(title = 'Math Score'),
                  yaxis = dict(title = 'Writing Score'),
                  width = 900,
                  height = 600,
                  template = 'simple_white')

# 添加数据和布局
fig = go.Figure(data=data,layout=layout)   
#iplot(fig)
fig.show()

颜色渐变条设置:

In 7:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = [go.Scatter(x = df['reading score'],
                   y = df['writing score'],
                   mode = 'markers',
                   text=df['math score'],
                   marker=dict(size = 14,
                               color = df['math score'], # 颜色
                               showscale = True,
                               colorscale = 'Cividis',
                               colorbar = dict(title='Math Score'),
                               opacity = 0.6))]

layout = go.Layout(title=dict(text='Reading Score - Writing Score - Math Score',
                              y = 0.9,
                              x = 0.5,
                              xanchor = 'center',
                              yanchor = 'top'),
                   xaxis = dict(title = 'Reading Score'),
                   yaxis =dict(title = 'Writing Score'),
                   template='simple_white')

fig = go.Figure(data=data,layout=layout)
# iplot(fig)
fig.show()

基于for循环的散点图:

In 8:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
df['parental level of education'].value_counts() # 不同的学历水平

Out8:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
some college          226
associate's degree    222
high school           196
some high school      179
bachelor's degree     118
master's degree        59
Name: parental level of education, dtype: int64

In 9:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = []
for i in df['parental level of education'].unique():
    data.append(go.Scatter(x = df[df['parental level of education'] == i]['reading score'],
                           y = df[df['parental level of education'] == i]['math score'],
                           mode = 'markers',
                           name = str(i),
                           showlegend = True,
                           marker = dict(size = 12,
                                          opacity = 0.65)))

layout = go.Layout(title = 'Scores by Level of Education',
                   xaxis = dict(title='Reading Score'),
                   yaxis = dict(title='Math Score'),
                   template = 'plotly_white')

fig = go.Figure(data=data, layout = layout)
iplot(fig)

6 气泡图Bubble charts

In 10:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = [go.Scatter(x = df['reading score'],
                   y = df['writing score'],
                   mode = 'markers',
                   text = df['math score'],
                   marker = dict(size = df['math score'] * 0.5,  # 关键代码:通过指定字段来控制颜色大小
                                 color = '#FFAE00',
                                 showscale = False,
                                 opacity = 0.5,
                                 line = dict(color = 'black', 
                                             width = 0.5)))]

layout = go.Layout(title=dict(text = 'Reading Score - Writing Score - Math Score',
                              y = 0.9,
                              x = 0.5,
                              xanchor = 'center',
                              yanchor = 'top'),
                   xaxis = dict(title = 'Reading Score'),
                   yaxis = dict(title = 'Writing Score'),
                   template ='plotly_white')

fig = go.Figure(data = data, layout = layout)
#iplot(fig)
fig.show()

7 3D 散点图-3D Scatter plots

In 11:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
df.columns

Out11:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
Index(['gender', 'race/ethnicity', 'parental level of education', 'lunch',
       'test preparation course', 'math score', 'reading score',
       'writing score'],
      dtype='object')

In 12:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = go.Scatter3d(x = df['math score'],
                    y = df['reading score'],
                    z = df['writing score'],
                    mode = 'markers',
                    marker = dict(color = df['math score'],
                                  showscale = True,
                                  colorbar = dict(title = 'Weight'),
                                  colorscale = 'picnic',
                                  opacity = 0.7))

layout = go.Layout(title = dict(text='Math-Reading-Writing',
                                y = 0.9,
                                x = 0.5,
                                xanchor = 'center',
                                yanchor = 'top'),
                   scene = dict(xaxis = dict(title = 'math score'),
                                yaxis = dict(title = 'reading score'),
                                zaxis = dict(title = 'writing score')),
                   font = dict(size = 12),
                   template = 'plotly_white')

fig = go.Figure(data = data, layout = layout)
# iplot(fig)
fig.show()

8 线形图line charts

生成模拟数据

In 13:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
df1 = pd.DataFrame({'date': [date(year = 2015 + i, month = 1, day = 1) for i in range(10)],
                    'students': np.random.randint(25,60,10),
                    'lecturers': np.random.randint(10, 20, 10)})

df1

Out13:

date

students

lecturers

0

2015-01-01

46

13

1

2016-01-01

26

17

2

2017-01-01

42

19

3

2018-01-01

31

10

4

2019-01-01

56

15

5

2020-01-01

34

13

6

2021-01-01

27

14

7

2022-01-01

42

18

8

2023-01-01

54

11

9

2024-01-01

44

19

In 14:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 基于px

fig = px.line(df1,x="date",y="students")
fig.show()

另一种方法:

In 15:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 基于go
line = [go.Scatter(x = df1['date'],
                   y = df1['students'],
                   mode = 'lines')] 

fig = go.Figure(data = line)
fig.show()

自定义标题、xy轴名称等:

In 16:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = go.Scatter(x = df1['date'],
                  y = df1['students'],
                  mode = 'lines',
                  name = 'students')

layout = go.Layout(title={'text': "Number of Students by Years",
                          'y':0.9,
                          'x':0.5,
                          'xanchor': 'center',
                          'yanchor': 'top'},
                   xaxis = dict(title = 'Year'),
                   yaxis = dict(title = 'Student'),
                   template = 'plotly_white'  # 布局使用的模板
                  )

fig = go.Figure(data = data, layout = layout)
# iplot(fig)
fig.show()

同时使用多个数据,更新模板:

In 17:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 先生成两个数据
student = go.Scatter(x = df1['date'],
                     y = df1['students'],
                     mode = 'lines', 
                     name = 'students',
                     marker = dict(color = 'darkorange'))

lecturer = go.Scatter(x = df1['date'], 
                      y = df1['lecturers'],
                     mode = 'lines', 
                      name = 'lecturers',
                     marker = dict(color = 'royalblue'))

# 布局的设置
layout = go.Layout(title={'text': "Number of Students & Lecturers by Years",
                          'y':0.9,
                          'x':0.5,
                          'xanchor': 'center',
                          'yanchor': 'top'},
                   xaxis = dict(title = 'Year'),
                   template = 'plotly_dark')  # 换成黑色主题

# data数据以列表的形式
fig = go.Figure(data = [student, lecturer], layout = layout)
fig.show()

9 柱状图bar charts

In 18:

代码语言:python
代码运行次数:2
运行
AI代码解释
复制
x = df.groupby('gender').agg({'math score':'mean'}).reset_index()['gender']
x

Out18:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
0    female
1      male
Name: gender, dtype: object

In 19:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = go.Bar(x = df.groupby('gender').agg({'math score':'mean'}).reset_index()['gender'], # xy轴数据
              y = df.groupby('gender').agg({'math score':'mean'}).reset_index()['math score'],
              width = [0.5, 0.5], # 每个柱子的宽度
              # 待显示的文本、位置、字体大小及颜色
              text =round(df.groupby('gender').agg({'reading score':'mean'}).reset_index()['reading score'],2),
              textposition="inside",  # inside\outside\auto
              textfont=dict(size=26,color="deeppink"),
              # 柱体设置
              marker = dict(color = 'cornflowerblue',
                            opacity = 0.7,
                            line_color = 'black',
                            line_width = 1))

# 布局设置
layout = go.Layout(title='基于性别的数学平均分',
                   xaxis = dict(title='Gender'),
                   yaxis =dict(title='Math Score'),
                   width = 700,
                   height = 700,
#                    template = 'plotly_white'
                  )

fig=go.Figure(data = data, layout = layout)
fig.update_yaxes(range = [0, 100])

# iplot(fig)
fig.show()

10 分组柱状图grouped bar charts

In 20:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 生成3个数据轨迹
trace1 = go.Bar(x = df.groupby('gender').agg({'reading score':'mean'}).reset_index()['gender'],   # x-y-显示文本
                y = df.groupby('gender').agg({'reading score':'mean'}).reset_index()['reading score'],
                text = round(df.groupby('gender').agg({'reading score':'mean'}).reset_index()['reading score'],2),
                textposition = 'auto',  # 文本位置
                name = 'Reading Score',  # 名称
                textfont = dict(size = 16),  # 字体
                marker = dict(color = '#06F5E3', opacity = 0.65))  # 标记符号设置

trace2 = go.Bar(x = df.groupby('gender').agg({'writing score':'mean'}).reset_index()['gender'],
                y = df.groupby('gender').agg({'writing score':'mean'}).reset_index()['writing score'],
                text = round(df.groupby('gender').agg({'writing score':'mean'}).reset_index()['writing score'],2),
                textposition = 'auto',
                name = 'Writing Score',
                textfont = dict(size = 16),
                marker=dict(color='#FEAD00',opacity = 0.65))

trace3 = go.Bar(x = df.groupby('gender').agg({'math score':'mean'}).reset_index()['gender'],
                y = df.groupby('gender').agg({'math score':'mean'}).reset_index()['math score'],
                text =round(df.groupby('gender').agg({'math score':'mean'}).reset_index()['math score'],2),
                textposition= 'auto',
                name = 'Math Score',
                textfont = dict(size = 16),
                marker=dict(color='#CC00FE',opacity = 0.65))

layout = go.Layout(title={'text': "Avg Scores by Gender",
                          'x':0.5,'y':0.9,
                          'xanchor': 'center','yanchor': 'top'
                         },
                   barmode='group',
                   legend=dict(x=0.05,
                               y=1.0,
                               bgcolor='rgba(255, 255, 255, 0)',
                               bordercolor='rgba(255, 255, 255, 0)'),
                   xaxis = dict(title = 'Gender'),
                   yaxis = dict(title = 'Score'),
                   template ='plotly_white')

fig = go.Figure(data = [trace1,trace2,trace3],
                layout=layout)

fig.update_yaxes(range=[0,100])
iplot(fig)

11 堆叠柱状图stacked bar charts

In 21:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
df.groupby(['parental level of education']).mean() # 基于某个字段的均值

Out21:

math score

reading score

writing score

parental level of education

associate's degree

67.882883

70.927928

69.896396

bachelor's degree

69.389831

73.000000

73.381356

high school

62.137755

64.704082

62.448980

master's degree

69.745763

75.372881

75.677966

some college

67.128319

69.460177

68.840708

some high school

63.497207

66.938547

64.888268

In 22:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
parental_avg = pd.DataFrame(df.groupby(['parental level of education']).mean())
parental_avg = parental_avg.reset_index()

trace1 = go.Bar(x = parental_avg['parental level of education'],  # 字段的唯一值信息
                y = parental_avg['math score'],  
                name = 'math score',
                marker = dict(color ='#F2E80C',opacity = 0.7))

trace2 = go.Bar(x = parental_avg['parental level of education'],
                y = parental_avg['reading score'],
                name ='reading score',
                marker = dict(color ='#44F20C',opacity = 0.7))

trace3 = go.Bar(x = parental_avg['parental level of education'],
                y = parental_avg['writing score'],
                name='writing score',
                marker = dict(color = '#F20CE1',opacity = 0.7))

layout = go.Layout(title = 'Avg Scores by Level of Education',
                   barmode = 'stack',
                   xaxis = dict(title='Level of Education'),
                   yaxis =dict(title='Score'),
                   template = 'plotly_dark')

fig = go.Figure(data = [trace1, trace2, trace3], layout=layout)
fig.show()

12 箱型图Box plots

基础柱状图:

In 23:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = go.Box(y=df['math score'],  # 待绘图的数据
              name = 'Math Score',
              marker_color='#91E26B')

layout = go.Layout(title={'text': "Math Score", 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'},
                   width = 600,
                   height = 600)

fig = go.Figure(data = data, layout=layout)
fig.show()

同时绘制子图和箱型图:

In 24:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
fig = make_subplots(rows=1,  # 子图1*2
                    cols=2,
                    shared_yaxes=True, # 共享y轴
                    subplot_titles=("Male", "Female")  # 子图名称
                   )

fig.add_trace(go.Box(y =df[df['gender']=='male']['writing score'],  # male----writing
                     showlegend=False,
                     name = 'Writing Score',
                     marker_color='#1760E1'),
              row=1,col=1)

fig.add_trace(go.Box(y =df[df['gender']=='male']['math score'],  # male----math
                     showlegend=False ,
                     name = 'Math Score',
                     marker_color='#17E160'),
              row=1,col=1)

fig.add_trace(go.Box(y =df[df['gender']=='male']['reading score'],  # male----reading
                     showlegend=False ,
                     name = 'Reading Score',
                     marker_color='#E1E117'),
              row=1,col=1)

fig.add_trace(go.Box(y =df[df['gender']=='female']['writing score'],  #  female----writing
                     showlegend=False,
                     name = 'Writing Score',
                     marker_color='#1760E1'),
              row=1,col=2)

fig.add_trace(go.Box(y =df[df['gender']=='female']['math score'] ,   #   female----math
                     showlegend=False,
                     name = 'Math Score',
                     marker_color='#17E160'),
              row=1,col=2)

fig.add_trace(go.Box(y =df[df['gender']=='female']['reading score'],   # female----reading
                     showlegend=False ,
                     name = 'Reading Score',
                     marker_color='#E1E117'),
              row=1,col=2)

fig.update_layout(title={'text': "Scores by Gender",
                         'y':0.9,
                         'x':0.5,
                         'xanchor': 'center',
                         'yanchor': 'top'},
                  width = 800,
                  height= 450,
                  template='plotly')      
fig.show()

13 饼图pie charts

In 25:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
colors = ['#28F20C', '#0CF2F2', '#F27F0C', '#F20C52']

fig = go.Figure(data=[go.Pie(labels = df['race/ethnicity'].value_counts().keys(),  # 字段的唯一值信息
                             values = df['race/ethnicity'].value_counts().values)])  # 不同的数量

fig.update_traces(hoverinfo='value',   # 悬停信息
                  textinfo='label',  # 每个扇形显示的信息 
                  textfont_size=16,  # 字体大小和位置
                  textposition ='auto',
                  showlegend=False,  # 不显示图例
                  #marker=dict(colors=colors) # 颜色设置
                 )

fig.update_layout(title={'text': "Race/Ethnicity Gropus",
                         'y':0.9,
                         'x':0.5,
                         'xanchor': 'center',
                         'yanchor': 'top'},
                 template='simple_white')

# iplot(fig)
fig.show()

可以绘制扇形区域图:

In 26:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
colors = ['#14CFE8', '#E814C1']

fig = go.Figure(data=[go.Pie(labels = df['lunch'].value_counts().keys(),
                             values = df['lunch'].value_counts().values,
                             pull = [0, 0.25])])  # 控制每个扇形区块的偏离程度

fig.update_traces(hoverinfo ='label',
                  textinfo ='percent',
                  textfont_size = 20,
                  textposition ='auto',
                  marker=dict(colors=colors,
                              line = dict(color = 'black', width = 1.5)))

fig.update_layout(title={'text': "Percentages of Lunch Types",
                         'x':0.5,
                         'y':0.9,
                         'xanchor': 'center',
                         'yanchor': 'top'},
                  template='plotly_white')

# iplot(fig)
fig.show()

14 甜甜圈图Donut Charts

主要是通过hole属性来控制:

In 27:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
colors = ['#D7DD19', '#6FDD19', '#19DDA5', '#195ADD','#A219DD','#DD1984']

fig = go.Figure(data=[go.Pie(labels = df['parental level of education'].value_counts().keys(),
                             values = df['parental level of education'].value_counts().values)])

fig.update_traces(hoverinfo='label',
                  textinfo='value',
                  hole = 0.4,  # 内圈的大小
                  textfont_size = 22,
                  textposition ='auto',
                  marker=dict(colors = colors,
                              line = dict(color = 'white',
                                          width = 2)))

fig.update_layout(title={'text': "Parental Level of Education",
                         'y':0.9,
                         'x':0.5,
                         'xanchor': 'center',
                         'yanchor': 'top'},
                          template='simple_white')

fig.show()

15 直方图histograms

In 28:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = [go.Histogram(x = df['math score'],  # 待绘制的数据
                     xbins = dict(start = 0, # 起始值和间隔
                                  end = 100,
                                  size = 5),
                     marker=dict(color ='#FFE400',  # 箱体的颜色、线形颜色和宽度
                                 line = dict(color='black',width=2))
                    )
       ]

layout = go.Layout(title ='直方图绘制',
                   xaxis = dict(title='Score'),
                   yaxis =dict(title='Frequency'),
                   width=700,
                   height=450, 
                   template = 'simple_white'
                  )

fig = go.Figure(data = data, layout = layout)

iplot(fig)

分组的直方图:

In 29:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
fig = go.Figure()

# 添加两个数据
fig.add_trace(go.Histogram(x=df[df['gender']=='male']['reading score'], # male数据
                           # 箱体起止点、间隔
                           xbins = dict(start = 0,end =100,size =5),
                           name='Male',
                           marker=dict(color = '#0891EF',opacity = 0.5)))

fig.add_trace(go.Histogram(x=df[df['gender']=='female']['reading score'],
                           xbins = dict(start = 0,end =100, size =5),
                           name='Female',
                           marker =dict(color ='#FF00E0',opacity = 0.5)))

fig.update_layout(title='Reading Scores Histogram',
                  barmode='overlay',
                  xaxis = dict(title='Score'),
                  yaxis =dict(title='Frequency'),
                  width=700,
                  height=450)
fig.show()

16 核密度图Distplots

distplots图是一种用于展示数值数据的统计表示的图形,它结合了直方图、核密度估计或正态曲线以及地毯图。distplots图提供了一种灵活的方式来观察和分析单变量观测值的分布特征。

In 30:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
hist_data = []
group_labels=[]

for i in range(len(df['race/ethnicity'].unique())):  # 唯一值长度
    hist_data.append(df[df['race/ethnicity'] == df['race/ethnicity'].unique()[i]]['math score'])  # 唯一值对应的math score数据
    group_labels.append(df['race/ethnicity'].unique()[i])  # 唯一值数据

# 绘制核密度图
fig = ff.create_distplot(hist_data, group_labels, bin_size=5)

fig.update_layout(title={'text': "Math Scores Distplot",
                         'y':0.9,
                         'x':0.5,
                         'xanchor': 'center',
                         'yanchor': 'top'},
                  barmode='overlay',
                  template='plotly_white')

fig.show()

17 热力图heatmap

In 31:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
fig = go.Figure(go.Heatmap(x=df['gender'],
                    y= df['test preparation course'],
                    z = df['math score'].values.tolist()))
fig.show()

绘制进阶版的热力图:

In 32:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = [go.Heatmap(x=df['gender'],
                   y= df['parental level of education'],
                   z = df['math score'].values.tolist(),  # 颜色条
                   colorscale = 'Magma')]

layout = go.Layout(title={'text': "Gender & Level of Education",
                          'y':0.9,
                          'x':0.5,
                          'xanchor': 'center',
                          'yanchor': 'top'},
                   xaxis = dict(title='Gender'),
                   yaxis =dict(title='Level of Education'),
                   width=600,
                   height=450,
                   template='plotly_white')

fig = go.Figure(data = data, layout = layout)
iplot(fig)

18 子图make_subplots

18.1 子图之线形图

In 33:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
# 子图设置
fig = make_subplots(rows = 1, # 行列设置
                    cols = 2,
                    shared_yaxes = True,  # 共享y轴
                    subplot_titles = ("2015-2019", "2020-2024"))  # 子标题设置

# 添加2个轨迹数据
fig.add_trace(go.Scatter(x = df1['date'][0:5],  # xy数据
                         y = df1['students'][0:5],
                         mode = 'lines',  # 模式:线形
                         showlegend = False,  # 不显示legend
                         name = 'students15-19', # 标题
                         line = dict(color = '#18FF01',  # 线属性
                                     width = 3,
                                     dash = 'dashdot')),
              row=1, col=1)
                                      
fig.add_trace(go.Scatter(x = df1['date'][5:10],
                         y = df1['students'][5:10],
                         mode = 'lines',
                         showlegend = False,
                         name = 'students20-24',
                         line = dict(color = '#01AAFF',
                                     width = 3,
                                     dash = 'dash')),
              row=1, col=2)

# 子图中y轴名称设置
fig.update_yaxes(title_text = "Students", row=1, col=1)
fig.update_yaxes(title_text = "Students", row=1, col=2)

# 布局设置
fig.update_layout(title=dict(text ='Number of Students by Years',
                             y = 0.9,
                             x = 0.5,
                             xanchor = 'center',
                             yanchor = 'top'),
                  template = 'plotly_dark')  # 主题

# iplot(fig)
fig.show()

18.2 子图之箱型图

绘制多个箱型图:

In 34:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
data = [go.Box(x =df['reading score'],
               showlegend=True,
               name = 'Reading Score'),
        go.Box(x=df['writing score'],
               showlegend=True,
               name = 'Writing Score'),
        go.Box(x=df['math score'],
               showlegend=True,
               name = 'Math Score')]

layout = go.Layout(title={'text': "Scores",
                          'y':0.9,
                          'x':0.5,
                          'xanchor': 'center',
                          'yanchor': 'top'},
                   width = 700,
                   height=450,
                   #template='plotly_dark'
                  )

fig = go.Figure(data = data, layout = layout)
fig.show()

18.3 不同图形的子图

In 35:

代码语言:python
代码运行次数:0
运行
AI代码解释
复制
colors = ['#4BA7CF','#CF5B4B','#B764D6','#E3885B','#5BE3E1']

fig = make_subplots(rows=1,cols=2,  # 子图1*2
                    subplot_titles=('Countplot','Percentages'), # 子图标题
                    specs=[[{"type": "xy"},  # 每个子图的类型
                            {'type':'domain'}]])
# 子图1:柱状图
fig.add_trace(go.Bar( y = df['race/ethnicity'].value_counts().values.tolist(), 
                      x = df['race/ethnicity'].value_counts().index, 
                      text=df['race/ethnicity'].value_counts().values.tolist(),  # 显示的数据
                      textfont=dict(size = 18, color = 'white'),
                      name='race/ethnicity',
                      textposition = 'auto',
                      showlegend=False,
                      marker=dict(color = colors)),
              row = 1, col = 1)

# 子图2:饼图
fig.add_trace(go.Pie(labels=df['race/ethnicity'].value_counts().keys(),
                     values=df['race/ethnicity'].value_counts().values,
                     textfont = dict(size = 18,
                                     color = 'white'),
                     textposition='auto',
                     showlegend = False,
                     name = 'race/ethnicity',
                     marker=dict(colors = colors)),
              row = 1, col = 2)

fig.update_layout(title={'text': 'Race/Ethnicity',
                         'y':0.9,
                         'x':0.5,
                         'xanchor': 'center',
                         'yanchor': 'top'},
                  template='plotly_dark'
                 )

fig.show()

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
可视化神器Plotly的图例Legend详解
很久没有更新Plotly相关的文章,国庆这几天终于干了一篇。选择的主题是:玩转Plotly图例设置,也是一直以来都想写的一个话题,文章的主要内容为:
皮大大
2021/10/07
2.6K0
plotly-express-17-plotly绘图技巧之图例与标题(二)
https://plotly.com/python/reference/#layout
皮大大
2021/03/01
4.6K0
plotly-express-17-plotly绘图技巧之图例与标题(二)
8个plotly绘图技巧
Plotly 是一个用于创建交互式数据可视化的 Python 库,它允许你轻松地生成各种类型的图表和图形,包括折线图、散点图、柱状图、饼图、热力图、3D 图等。
皮大大
2023/09/17
8930
Plotly深入浅出
作为Python的新一代数据可视化绘图库,和matplotlib等传统绘图库相比,plotly具有以下优点:
lyhue1991
2022/05/16
2.6K0
Plotly深入浅出
plotly-express-22-plotly使用技巧大全
本文中将前段时间写的plotly-express可视化库的相关技巧进行整理,方便后续快速实现调用
皮大大
2021/03/01
3.1K0
plotly-express-22-plotly使用技巧大全
数据科学家赚多少?基于pandasql和plotly的薪资分析与可视化 ⛵
图片 本文揭秘全球数据科学岗位的薪资分布情况!以及分析岗位、国家、工作经验、雇佣形式、公司规模对薪资的影响,并贴心提供了求职建议和跳槽Tips! 💡 作者:韩信子@ShowMeAI 📘 数据分析实战系列:https://www.showmeai.tech/tutorials/40 📘 AI 岗位&攻略系列:https://www.showmeai.tech/tutorials/47 📘 本文地址:https://www.showmeai.tech/article-detail/402 📢 声明:版权所有,
ShowMeAI
2022/12/09
1.2K0
数据科学家赚多少?基于pandasql和plotly的薪资分析与可视化 ⛵
plotly-express-9-plotly实现线型图
本文中介绍的是利用plotly绘制线型图,使用的是line()和go.Line()方法
皮大大
2021/03/01
1.8K0
plotly-express-9-plotly实现线型图
可视化神器Plotly玩转股票图
本文是可视化神器Plotly绘图的第7篇,讲解的是如何通过Plotly来绘制与股市相关的图形,比如基础K线图、OHLC图等。
皮大大
2021/04/28
6.8K0
可视化神器Plotly玩转股票图
plotly-express-8-plotly实现散点图
本文中介绍的是利用plotly_express绘制散点图,使用的是scatter()方法。
皮大大
2021/03/01
1.7K0
plotly-express-8-plotly实现散点图
Plotly 初步
版权声明:本文为博主原创文章,未经授权禁止转载。 https://blog.csdn.net/u010099080/article/details/84197684
Alan Lee
2019/05/27
1.3K0
厉害了,“plotly”也能画出高颜值的组合图
今天小编和大家分享一下“组合图”的绘制,在我们的日常生活工作当中,通常都会遇到需要去绘制“组合图”,例如折线图和直方图的组合,那么如何将“组合图”绘制的高颜值一点、通俗易懂一点呢?
用户6888863
2021/07/19
1.9K0
plotly-express-16-绘制技巧(一)
Plotly-express-16-绘制技巧(一) 本文中介绍的是利用Plotly绘图小技巧: 图片的保存:jupyter notebook下的保存和指定路径下的保存 柱状图的颜色改变(避免同样的颜色
皮大大
2021/03/01
1.3K0
plotly-express-16-绘制技巧(一)
使用Python实现网络数据的可视化:NetworkX与Plotly的应用探索
随着网络科学的快速发展和数据规模的不断扩大,如何有效地可视化和分析网络数据变得越来越重要。本文将介绍如何使用Python中的NetworkX和Plotly库来进行网络数据的可视化。
一键难忘
2024/09/29
5860
plotly-express-13-plotly生成表格
https://plotly.com/python/figure-factory-table/
皮大大
2021/03/01
1.6K0
plotly-express-13-plotly生成表格
plotly-express-15-plotly绘制水平柱状图
In this example a column is used to color the bars, and we add the information from other columns to the hover data.
皮大大
2021/03/01
1.5K0
plotly-express-15-plotly绘制水平柱状图
plotly可视化快速教程
Plotly是新一代的Python数据可视化开发库,它提供了完善的交互能力和灵活的绘制选项。本文将介绍新手如何安装plotly并编写第一个plotly绘图程序,以及使用plotly绘制常见的5种数据图表。
用户1408045
2019/10/10
2.9K0
plotly可视化快速教程
Plotly,一个超强的Python可视化库!
数据可视化是数据分析和探索的一个重要方面,它有助于深入了解数据集中的潜在模式、趋势和关系。
小F
2023/12/21
7290
Plotly,一个超强的Python可视化库!
高级可视化神器Plotly玩转散点图
之前介绍过一篇文章介绍酷炫!36张图爱上高级可视化神器Plotly_Express,文章中大量介绍了基于plotly绘制的各种图形,例子多而不精彩。本文开始将会详细介绍基于Plotly绘制的各种图形,Plotly绘图中主要是两个模块:
皮大大
2021/04/19
2.1K0
高级可视化神器Plotly玩转散点图
深入了解 Plotly 高级技术,附实用代码示例
数据可视化是数据分析和探索中至关重要的一部分,能够帮助我们更深入地理解数据集中的潜在模式、趋势和关系。Plotly是一个功能强大、用途广泛的Python库,提供了多种工具用于创建交互式、视觉上引人入胜的图表。在本文中,我们将深入探索Plotly的世界,通过高级Python代码示例来探索其特性和功能。
数据STUDIO
2024/04/11
7670
深入了解 Plotly 高级技术,附实用代码示例
高级可视化神器Plotly玩转散点图
之前介绍过一篇文章介绍酷炫!36张图爱上高级可视化神器Plotly_Express,文章中介绍了大量基于plotly绘制的各种图形,例子多而不精。本文开始将会详细介绍基于Plotly绘制的各种图形,Plotly绘图主要是两个模块:
皮大大
2021/04/07
2.4K0
高级可视化神器Plotly玩转散点图
相关推荐
可视化神器Plotly的图例Legend详解
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验