Background
一、st.altair_chart 画图源码和效果
- 首先需要安装依赖
pip install altair vega_datasets - 下图中右面的折线图是代码效果哈
import altair as alt
import pandas as pd
import streamlit as st
from vega_datasets import data
@st.experimental_memo
def get_data():
source = data.stocks()
source = source[source.date.gt("2004-01-01")]
return source
source = get_data()
def get_chart(data):
hover = alt.selection_single(
fields=["date"],
nearest=True,
on="mouseover",
empty="none",
)
lines = (
alt.Chart(data, title="Evolution of stock prices")
.mark_line()
.encode(
x="date",
y="price",
color="symbol",
)
)
points = lines.transform_filter(hover).mark_circle(size=65)
tooltips = (
alt.Chart(data)
.mark_rule()
.encode(
x="yearmonthdate(date)",
y="price",
opacity=alt.condition(hover, alt.value(0.3), alt.value(0)),
tooltip=[
alt.Tooltip("date", title="Date"),
alt.Tooltip("price", title="Price (USD)"),
],
)
.add_selection(hover)
)
return (lines + points + tooltips).interactive()
chart = get_chart(source)
st.altair_chart(chart, use_container_width=True)
下面介绍保存图片功能所需依赖的配置过程(Selenium)
1、安装python依赖库
pip install altair_saver selenium
2、在Centos7上安装Chrome浏览器和ChromeDriver
我是在Centos7上,你要是在ubuntu上的话请用apt-get安装。
yum install https://dl.google.com/linux/direct/google-chrome-stable_current_x86_64.rpm
google-chrome --version
wget http://chromedriver.storage.googleapis.com/99.0.4844.51/chromedriver_linux64.zip
unzip chromedriver_linux64.zip
chmod a+x chromedriver
cp chromedriver /usr/bin/
chromedriver --version
最终打印信息无报错说明安装成功。
from selenium import webdriver
ch_options = webdriver.ChromeOptions()
ch_options.add_argument("--headless")
ch_options.add_argument('--no-sandbox')
ch_options.add_argument('--disable-gpu')
ch_options.add_argument('--disable-dev-shm-usage')
dr = webdriver.Chrome(options=ch_options)
url = "https://www.baidu.com"
dr.get(url)
print(dr.page_source)
3、添加图片保存代码
from altair_saver import save as save_chart
save_chart(chart, "chart.png")
|