Altair绘制实时数据Python



如何在Python中使用Altair实时绘制?我有1个按熊猫分组的数据。我不知道如何用分组数据实时绘制altair实时图。这是我的代码:

import mainData
import altair as alt
alt.renderers.enable('altair_viewer')
import time
while True:
mainData.realTime()
chart0 = alt.Chart(mainData.grouped.get_group(0, obj=None).reset_index()).transform_fold(mainData.grouped.get_group(0, obj=None).columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q', color='quote:N')
chart1 = alt.Chart(mainData.grouped.get_group(1, obj=None).reset_index()).transform_fold(mainData.grouped.get_group(1, obj=None).columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q', color='quote:N')
chart2 = alt.Chart(mainData.grouped.get_group(2, obj=None).reset_index()).transform_fold(mainData.grouped.get_group(2, obj=None).columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q', color='quote:N')
chart3 = alt.Chart(mainData.grouped.get_group(3, obj=None).reset_index()).transform_fold(mainData.grouped.get_group(3, obj=None).columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q', color='quote:N')
chart4 = alt.Chart(mainData.grouped.get_group(4, obj=None).reset_index()).transform_fold(mainData.grouped.get_group(4, obj=None).columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q', color='quote:N')
chart5 = alt.Chart(mainData.grouped.get_group(5, obj=None).reset_index()).transform_fold(mainData.grouped.get_group(5, obj=None).columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q', color='quote:N')
alt.vconcat(alt.hconcat(chart0, chart1, chart2), alt.hconcat(chart3, chart4, chart5)).show()
time.sleep(0.2)

我已经在网页上绘制了图表显示,但show((阻止了我的循环,所以我无法在while loop中重新创建分组数据。分组数据是mainData.realtime((中的全局变量。如何在浏览器上显示Altair的图表而不显示((?或者如何使用Altair在while循环中实时绘制图表?提前谢谢。最小示例:

import pandas as pd
import numpy as np
import time
import altair as alt
alt.renderers.enable('altair_viewer')
while True:
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
chart0 = alt.Chart(df.reset_index()).transform_fold(df.columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q', color='quote:N')
chart0.show()
print("1")
time.sleep(0.5)

我已经有了答案,Altair使用Streamlit实时绘制图表。谢谢你的伙伴们:D。我关注这篇文章:https://towardsdatascience.com/how-to-run-animations-in-altair-and-streamlit-2a0624789ad.

这是我的代码:

import pandas as pd
import numpy as np
import time
import altair as alt
import streamlit as st
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
def draw(df):
chart = alt.Chart(df.reset_index()).transform_fold(df.columns.tolist(), as_=['quote', 'price']).mark_line().encode(x='index:T', y='price:Q')
return chart
draw(df)
realTimeChart = st.altair_chart(chart)
while True:
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
draw(df)
realTimeChart = realTimeChart.altair_chart(chart)
time.sleep(0.2)

最新更新