streamlit

streamlit – The fastest way to build and share data apps 是专门针对机器学习和数据科学团队的应用开发框架,你可以认为它的目标是取代Flask在机器学习项目中的地位从而帮助机器学习工程师快速开发用户交互工具。

源码传送门: https://github.com/streamlit/streamlit

关于streamlit的介绍和教程网上可以搜到,不再做过多的冗余介绍,当然本篇依旧是入门篇,不过我们会用实际的数据来看一下它基本的效果。我们要用DogeCoin狗狗币的历史数据来画一些有意思的图,并利用streamlit来展示出来,整个过程也是对streamlit的初步认识。废话不多说,开始撸代码。

1、安装

pip install streamlit

2、狗狗币数据一览

DogeCoin数据一览、

3、引入相关python包

import streamlit as st
import pandas as pd
import plotly.graph_objects as go

4、自定义函数

# 加载数据
def load_dogecoin_data():
    ss = pd.read_csv("D:/path/to/dogecoin/doge_history.csv")
    ss = ss.set_index(pd.DatetimeIndex(ss['tickertime']))
    ss = ss.drop(columns=['Unnamed: 0', 'tickertime'])
    ss = ss.sort_index()
    return ss

# 设置开始结束日期
def get_inputs():
    # 设置边框输入栏
    start_date = st.sidebar.text_input("开始日期:", "2019-12-01")
    end_date = st.sidebar.text_input("结束日期:", "2021-05-16")
    return start_date, end_date

# 按日期加载数据
def get_data(start, end):
    data = load_dogecoin_data()
    start = pd.to_datetime(start)
    end = pd.to_datetime(end)
    return data.loc[start: end]

5、数据初始化

_start, _end = get_inputs()
df = get_data(_start, _end)

6、各种画图

fig = go.Figure(data=[go.Candlestick(
    x=df.index,
    open=df['openprice'],
    close=df['closeprice'],
    high=df['high'],
    low=df['low'],
    increasing_line_color='red',
    decreasing_line_color='green'
)])

st.title('Analysis DogeCoin by Streamlit!')
st.header('DogeCoin data')
st.write(df)
st.header('DogeCoin Statistics')
st.write(df.describe())
st.header('DogeCoin Volume')
st.bar_chart(df['vol'])
st.header('DogeCoin Close Price')
st.line_chart(df['closeprice'])
st.header('DogeCoin Candle Stick')
st.plotly_chart(fig)

7、运行

streamlit run streamlit_app.py

8、效果展示

我们可以在浏览器中看到运行的效果,打开浏览器输入地址,http://localhost:8501/

streamlit sidebar效果

在浏览器的左侧边框可以看到初始化的文本框,我们可以自己手动输入日期,然后按回车,那么浏览器对应的其它图会自动从新加载指定日期的数据。

streamlit 基本效果图标1
streamlit 基本效果图2

整个浏览器中看到的图都是动态的,可以通过鼠标滚动或者单击挪动图的具体内容。

参考: https://zhuanlan.zhihu.com/p/85741306

python 之画图利器 Plotly

Plotly的Python图形库使互动的出版质量图表成为在线。 如何制作线图,散点图,面积图,条形图,误差线,箱形图,直方图,热图,子图,多轴,极坐标图和气泡图的示例。推荐使用jupyter notebook来展示Plotly的画图效果。如果不去按照本地实验,也可以在官方的线上demo中操作展示。

传送门:https://plotly.com/

友情提示:网上很多的Plotly教程提供的代码示例内容很有可能已经过时,大家学习时尽可能的去官方网址的最新Demo或者API中查看具体的使用方式,例如很多文章的代码示例会提到一个import的包就已经在最新的版本中不做历史兼容了

import plotly.plotly as py 这样引入的时候在新版本中会包该模块已经被合并到chart-studio中,这个时候就要从新安装这个包,并从这个包中引入该模块。

1、安装

pip install plotly

2、代码示例

闲话少扯,直接上一些代码示例来简单撸一下效果。

2.1 线图

import plotly.graph_objects as go
import numpy as np
x = np.arange(10)
fig = go.Figure(data=go.Scatter(x=x, y=x**2))
fig.show()
Plotly 线图

2.2 点图

import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species",size='petal_length', hover_data=['petal_width'])
fig.show()
Plotly 点图

2.3 饼图

import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")
df.loc[df['pop'] < 2.e6, 'country'] = 'Other countries' # Represent only large countries
fig = px.pie(df, values='pop', names='country', title='Population of European continent')
fig.show()
Plotly 饼图

2.4 表格

import plotly.graph_objects as go

headerColor = 'grey'
rowEvenColor = 'lightgrey'
rowOddColor = 'white'

fig = go.Figure(data=[go.Table(
  header=dict(
    values=['<b>EXPENSES</b>','<b>Q1</b>','<b>Q2</b>','<b>Q3</b>','<b>Q4</b>'],
    line_color='darkslategray',
    fill_color=headerColor,
    align=['left','center'],
    font=dict(color='white', size=12)
  ),
  cells=dict(
    values=[
      ['Salaries', 'Office', 'Merchandise', 'Legal', '<b>TOTAL</b>'],
      [1200000, 20000, 80000, 2000, 12120000],
      [1300000, 20000, 70000, 2000, 130902000],
      [1300000, 20000, 120000, 2000, 131222000],
      [1400000, 20000, 90000, 2000, 14102000]],
    line_color='darkslategray',
    # 2-D list of colors for alternating rows
    fill_color = [[rowOddColor,rowEvenColor,rowOddColor, rowEvenColor,rowOddColor]*5],
    align = ['left', 'center'],
    font = dict(color = 'darkslategray', size = 11)
    ))
])

fig.show()
Plotly 表格

2.5 3D图

import plotly.graph_objects as go
from plotly.subplots import make_subplots

import numpy as np

# Initialize figure with 4 3D subplots
fig = make_subplots(
    rows=2, cols=2,
    specs=[[{'type': 'surface'}, {'type': 'surface'}],
           [{'type': 'surface'}, {'type': 'surface'}]])

# Generate data
x = np.linspace(-5, 80, 10)
y = np.linspace(-5, 60, 10)
xGrid, yGrid = np.meshgrid(y, x)
z = xGrid ** 3 + yGrid ** 3

# adding surfaces to subplots.
fig.add_trace(
    go.Surface(x=x, y=y, z=z, colorscale='Viridis', showscale=False),
    row=1, col=1)

fig.add_trace(
    go.Surface(x=x, y=y, z=z, colorscale='RdBu', showscale=False),
    row=1, col=2)

fig.add_trace(
    go.Surface(x=x, y=y, z=z, colorscale='YlOrRd', showscale=False),
    row=2, col=1)

fig.add_trace(
    go.Surface(x=x, y=y, z=z, colorscale='YlGnBu', showscale=False),
    row=2, col=2)

fig.update_layout(
    title_text='3D subplots with different colorscales',
    height=800,
    width=800
)

fig.show()
Plotly 3D效果图