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

Plotly绘图,快速入门

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

公众号:尤而小屋 编辑: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
代码运行次数:0
运行
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 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
从0开始构建一个Oauth2Server服务 <15> 安全问题
针对 OAuth 服务器的一种潜在Attack是网络钓鱼Attack。这是Attack者创建一个看起来与服务授权页面相同的网页的地方,该页面通常包含用户名和密码字段。然后,Accacker可以通过各种手段诱骗用户访问该页面。除非用户可以检查浏览器的地址栏,否则该页面可能看起来与真正的授权页面完全相同,并且用户可以输入他们的用户名和密码。
用户1418987
2023/10/16
2870
从0开始构建一个Oauth2Server服务 <15> 安全问题
从0开始构建一个Oauth2Server服务 <25> Native App 使用OAuth
为本机应用程序支持 OAuth 时要牢记的一些特殊注意事项。与基于浏览器的应用程序一样,本机应用程序不能使用客户端机密,因为这将要求开发人员在应用程序的二进制分发中传送机密。事实证明,反编译和提取秘密相对容易。因此,本机应用程序必须使用不需要预注册客户端密码的 OAuth 流程。
用户1418987
2023/10/16
2890
从0开始构建一个Oauth2Server服务 <25> Native App 使用OAuth
从0开始构建一个Oauth2Server服务1-创建应用程序
我们将介绍在构建与现有 OAuth 2.0 API 对话的应用程序时需要了解的事项。无论您是构建 Web 应用程序还是移动应用程序,在我们开始时都需要牢记一些事项。
用户1418987
2023/10/16
2340
从0开始构建一个Oauth2Server服务1-创建应用程序
从0开始构建一个Oauth2Server服务 <6> 移动和本机应用程序
与单页应用程序一样,移动应用程序也无法维护客户机密。因此,移动应用程序还必须使用不需要客户端密码的 OAuth 流程。当前的最佳做法是将授权流程与 PKCE 一起使用,同时启动外部浏览器,以确保本机应用程序无法修改浏览器窗口或检查内容。
用户1418987
2023/10/16
3880
从0开始构建一个Oauth2Server服务 <6> 移动和本机应用程序
从0开始构建一个Oauth2Server服务 <18> AccessToken
访问令牌是应用程序用来代表用户发出 API 请求的东西。访问令牌代表特定应用程序访问用户数据的特定部分的授权。
用户1418987
2023/10/16
6160
从0开始构建一个Oauth2Server服务 <18> AccessToken
从0开始构建一个Oauth2Server服务 <5> 单页应用
单页应用程序(也称为基于浏览器的应用程序)在从网页加载 JavaScript 和 HTML 源代码后完全在浏览器中运行。由于浏览器可以使用整个源代码,因此它们无法维护客户端机密的机密性,因此这些应用程序不使用机密。因为他们不能使用客户端密码,所以最好的选择是使用 PKCE 扩展来保护重定向中的授权代码。这类似于也不能使用客户端密码的移动应用程序的解决方案。
用户1418987
2023/10/16
4880
从0开始构建一个Oauth2Server服务 <5> 单页应用
从0开始构建一个Oauth2Server服务 <14> 授权响应
如果请求有效且用户同意授权请求,授权服务器将生成授权代码并将用户重定向回应用程序,将授权代码和应用程序的“状态”值添加到重定向 URL。
用户1418987
2023/10/16
3520
从0开始构建一个Oauth2Server服务 <14> 授权响应
从0开始构建一个Oauth2Server服务 <4> 构建服务器端应用程序
该应用程序通过制作包含客户端 ID、范围、状态和 PKCE 代码验证程序的 URL 来启动流程。该应用程序可以将其放入<a href="">标签中。
用户1418987
2023/10/16
3760
从0开始构建一个Oauth2Server服务 <4> 构建服务器端应用程序
从0开始构建一个Oauth2 Server服务 <3> 构建服务器端应用程序
服务器端应用程序是处理 OAuth 服务器时遇到的最常见的应用程序类型。这些应用程序在 Web 服务器上运行,其中应用程序的源代码不向公众开放,因此它们可以维护其客户端机密的机密性。
用户1418987
2023/10/16
4590
从0开始构建一个Oauth2 Server服务 <3> 构建服务器端应用程序
从0开始构建一个Oauth2Server服务 <12> 用户登录及授权
单击应用程序的“登录”或“连接”按钮后,用户首先会看到的是您的授权服务器 UI。由授权服务器决定是要求用户在每次访问授权屏幕时都登录,还是让用户在一段时间内保持登录状态。如果授权服务器在请求之间记住了用户,那么它可能仍需要请求用户的许可才能在以后的访问中授权应用程序。
用户1418987
2023/10/16
4210
从0开始构建一个Oauth2Server服务 <12> 用户登录及授权
从0开始构建一个Oauth2Server服务 <8> 注册应用
当开发人员访问您的网站时,他们将需要一种方法来创建新的应用程序并获取凭据。通常,在他们可以创建应用程序之前,您会让他们创建一个开发者帐户,或代表他们的组织创建一个帐户。
用户1418987
2023/10/16
2190
从0开始构建一个Oauth2Server服务 <8> 注册应用
Go语言中的OAuth2认证
在网络应用程序开发中,安全性和用户身份验证是至关重要的方面。OAuth2(开放授权2.0)是一种广泛应用于网络身份验证和授权的标准协议。它允许客户端应用程序以安全且受控的方式访问受保护资源,而无需用户提供其凭据。
繁依Fanyi
2024/04/15
1.1K0
从0开始构建一个Oauth2Server服务 <20> Access Token 访问令牌
当您的服务发出访问令牌时,您需要就您希望令牌持续多长时间做出一些决定。不幸的是,没有针对每项服务的一揽子解决方案。不同的选项会带来各种权衡,因此您应该选择最适合您的应用程序需求的选项(或选项组合)
用户1418987
2023/10/16
3830
从0开始构建一个Oauth2Server服务 <20> Access Token 访问令牌
「应用安全」OAuth和OpenID Connect的全面比较
在这篇文章中,从头开始实施OAuth 2.0和OpenID Connect服务器的开发人员(我)讨论了调查结果。基本上,实施的考虑点是在讨论中写出来的。因此,对于那些正在寻找“如何及时设置OAuth 2.0和OpenID Connect服务器”等信息的人来说,这不是一个文档。如果您正在寻找此类信息,请访问GitHub上的java-oauth-server和java-resource-server。使用这些,您可以在10分钟内启动授权服务器和资源服务器,发出访问令牌并使用访问令牌调用Web API,而无需设置数据库服务器。
架构师研究会
2019/09/03
2.8K0
「应用安全」OAuth和OpenID Connect的全面比较
Golang 如何实现一个 Oauth2 客户端程序
欢迎star demo007x/oauth2-client: Oauth2 Client package for Golang (github.com)
用户1418987
2023/10/16
6740
Golang 如何实现一个 Oauth2  客户端程序
OAuth 详解<2> 什么是 OAuth 2.0 授权码授权类型?
demo007x/oauth2-client: Oauth2 Client package for Golang (github.com) 欢迎star
用户1418987
2023/04/11
2.3K0
OAuth 详解<2> 什么是 OAuth 2.0 授权码授权类型?
OAuth 详解<4> 什么是 OAuth 2.0 隐式授权类型?
隐式授权类型是单页 JavaScript 应用程序无需中间代码交换步骤即可获取访问令牌的一种方式。它最初是为 JavaScript 应用程序(无法安全存储机密)而创建的,但仅在特定情况下才推荐使用。
用户1418987
2023/10/16
5430
OAuth 详解<4> 什么是 OAuth 2.0 隐式授权类型?
OAuth 2.0初学者指南
本文概述了OAuth 2.0协议。它讨论了OAuth 2.0实现过程中涉及的不同参与者和步骤。
银河1号
2019/05/16
2.7K0
OAuth 2.0初学者指南
从协议入手,剖析OAuth2.0(译 RFC 6749)
      传统的client-server授权模型,客户端通过使用凭证(通常的用户名和明文密码)访问服务端受保护的资源,为了能够让第三方应用程序访问受保护的资源,需要将凭证共享给第三方。
justmine
2022/05/10
5.3K0
OAuth 详解<1> 什么是 OAuth?
从高层次开始,OAuth 不是API或服务:它是授权的开放标准,任何人都可以实施它。
用户1418987
2023/04/10
5.2K0
OAuth 详解<1> 什么是 OAuth?
推荐阅读
相关推荐
从0开始构建一个Oauth2Server服务 <15> 安全问题
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验