Visualization Document Feb 12 16:42

文章目录

  • Visualization Document Feb 12 16:42
    • Page nav, PIE, and Line chart
    • PIE, and Line chart on differnet page
    • Table
    • Updated Table
    • Change the timeseries x axis to hours
    • Notes from Python Dash

Page nav, PIE, and Line chart

from dash import Dash, dcc, html,callback, Input, Output
import pandas as pd
import plotly.express as px
app = Dash(__name__)
#
df = pd.read_csv ('robot.txt', sep =' ')
#
df2 = df.set_axis(['Time', 'Power', 'Robot'], axis=1, inplace=False)#df3 = px.data.tips()# fig = px.pie(df2, values='Power', names='Robot')
# fig.show()
#print(df3)app.layout = html.Div([
html.H1(children='Hello Dash'),html.Div(children='''Dash: A web application framework for your data.'''),dcc.Location(id='url', refresh=False),dcc.Link('Navigate to "/"', href='/'),html.Br(),dcc.Link('Navigate to "/page-2"', href='/page-2'),# content will be rendered in this elementhtml.Div(id='page-content'),dcc.Graph(figure = px.pie(df2, values='Power', names='Robot')),dcc.Graph(figure=dict(data=[dict(x=df2['Time'],y=df2['Power'].loc[df2['Robot']=='robot1'],#df.loc[df['column_name'] == some_value]name='Robot 1',marker=dict(color='rgb(55, 83, 109)')),dict(x=df2['Time'],y=df2['Power'].loc[df2['Robot']=='robot2'],#df.loc[df['column_name'] == some_value]name='Robot 2',marker=dict(color='rgb(26, 118, 255)'))],layout=dict(title='Robot Power',showlegend=True,legend=dict(x=0,y=1.0),margin=dict(l=40, r=0, t=40, b=30))),style={'height': 300},id='my-graph')])@callback(Output('page-content', 'children'),[Input('url', 'pathname')])
def display_page(pathname):return html.Div([html.H3(f'You are on page {pathname}')])if __name__ == '__main__':app.run_server(debug=True)

PIE, and Line chart on differnet page

from dash import Dash, dcc, html, Input, Output, callback
import plotly.express as px
app = Dash(__name__, suppress_callback_exceptions=True)
import pandas as pddf = pd.read_csv ('robot.txt', sep =' ')
#
df2 = df.set_axis(['Time', 'Power', 'Robot'], axis=1, inplace=False)app.layout = html.Div([dcc.Location(id='url', refresh=False),html.Div(id='page-content')
])index_page = html.Div([dcc.Link('Pie chart', href='/page-1'),html.Br(),dcc.Link('Line chart', href='/page-2'),
])page_1_layout = html.Div([html.H1('Page 1'),dcc.Graph(figure=px.pie(df2, values='Power', names='Robot')),html.Div(id='page-1-content'),html.Br(),dcc.Link('Go to Line chart', href='/page-2'),html.Br(),dcc.Link('Go back to home', href='/'),
])@callback(Output('page-1-content', 'children'),[Input('page-1-dropdown', 'value')])
def page_1_dropdown(value):return f'You have selected {value}'page_2_layout = html.Div([html.H1('Page 2'),dcc.Graph(figure=dict(data=[dict(x=df2['Time'],y=df2['Power'].loc[df2['Robot'] == 'robot1'],  # df.loc[df['column_name'] == some_value]name='Robot 1',marker=dict(color='rgb(55, 83, 109)')),dict(x=df2['Time'],y=df2['Power'].loc[df2['Robot'] == 'robot2'],  # df.loc[df['column_name'] == some_value]name='Robot 2',marker=dict(color='rgb(26, 118, 255)'))],layout=dict(title='Robot Power',showlegend=True,legend=dict(x=0,y=1.0),margin=dict(l=40, r=0, t=40, b=30))),style={'height': 300},id='my-graph'),html.Div(id='page-2-content'),html.Br(),dcc.Link('Go to Pie Chart', href='/page-1'),html.Br(),dcc.Link('Go back to home', href='/')
])@callback(Output('page-2-content', 'children'),[Input('page-2-radios', 'value')])
def page_2_radios(value):return f'You have selected {value}'# Update the index
@callback(Output('page-content', 'children'),[Input('url', 'pathname')])
def display_page(pathname):if pathname == '/page-1':return page_1_layoutelif pathname == '/page-2':return page_2_layoutelse:return index_page# You could also return a 404 "URL not found" page hereif __name__ == '__main__':app.run_server(debug=True)

Table

Energy consumed Current energy Current power Current cost
Robot End of the column Dummy

page_3_layout = html.Div([html.H1('Page 3'),dash_table.DataTable(df2.to_dict('records'), [{"name": i, "id": i} for i in df2.columns]),html.Div(id='page-3-content'),html.Br(),dcc.Link('Go to Line chart', href='/page-3'),html.Br(),dcc.Link('Go back to home', href='/'),
])@callback(Output('page-3-content', 'children'),[Input('page-3-dropdown', 'value')])
def page_3_dropdown(value):return f'You have selected {value}'

Updated Table

d = {'Energy consumed': [1], 'Current energy': [3],'Current power': [3],'Current cost': [3]}
df3=pd.DataFrame(data=d)page_3_layout = html.Div([html.H1('Page 3'),dash_table.DataTable(df3.to_dict('records'), [{"name": i, "id": i} for i in df3.columns]),html.Div(id='page-3-content'),html.Br(),dcc.Link('Go to Line chart', href='/page-3'),html.Br(),dcc.Link('Go back to home', href='/'),
])@callback(Output('page-3-content', 'children'),[Input('page-3-dropdown', 'value')])
def page_3_dropdown(value):return f'You have selected {value}'

Change the timeseries x axis to hours

official website

import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x="date", y=df.columns,hover_data={"date": "|%B %d, %Y"},title='custom tick labels')
fig.update_xaxes(dtick="M1",tickformat="%b\n%Y")
fig.show()

from dash import Dash, dcc, html, Input, Output, callback, dash_table
import plotly.express as px
app = Dash(__name__, suppress_callback_exceptions=True)
import pandas as pd
from example import *df2 = read_example_csv()# dataframe for total energy frame df3
d = {'Energy consumed': [1], 'Current energy': [3],'Current power': [3],'Current cost': [3]}
df3=pd.DataFrame(data=d)# test for period
df_test = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')fig = px.line(df2, x=df2.index, y='Power', title='Time Series with Range Slider and Selectors')fig.update_xaxes(rangeslider_visible=True,rangeselector=dict(buttons=list([dict(count=1, label="1m", step="month", stepmode="backward"),dict(count=6, label="6m", step="month", stepmode="backward"),dict(count=1, label="YTD", step="year", stepmode="todate"),dict(count=1, label="1y", step="year", stepmode="backward"),dict(step="all")]))
)app.layout = html.Div([dcc.Location(id='url', refresh=False),html.Div(id='page-content')
])index_page = html.Div([dcc.Link('Pie chart', href='/page-1'),html.Br(),dcc.Link('Line chart', href='/page-2'),html.Br(),dcc.Link('Table', href='/page-3'),
])page_1_layout = html.Div([html.H1('Page 1'),dcc.Graph(figure=px.pie(df2, values='Power', names='Machine')),html.Div(id='page-1-content'),html.Br(),dcc.Link('Go to Line chart', href='/page-2'),html.Br(),dcc.Link('Go back to home', href='/'),
])@callback(Output('page-1-content', 'children'),[Input('page-1-dropdown', 'value')])
def page_1_dropdown(value):return f'You have selected {value}'page_2_layout = html.Div([html.H1('Page 2'),# dcc.Graph(#     figure = px.line(df2, x=df2.index, y='Power', title='Time Series with Range Slider and Selectors')# ),dcc.Graph(figure=dict(data=[dict(x=df2.index,y=df2['Power'].loc[df2['Machine'] == 'robot1'],  # df.loc[df['column_name'] == some_value]name='Robot 1',marker=dict(color='rgb(55, 83, 109)')),dict(x=df2.index,y=df2['Power'].loc[df2['Machine'] == 'robot2'],  # df.loc[df['column_name'] == some_value]name='Robot 2',marker=dict(color='rgb(26, 118, 255)'))],layout=dict(title='Robot Power',showlegend=True,legend=dict(x=0,y=1.0),margin=dict(l=40, r=0, t=40, b=30))),style={'height': 300},id='my-graph'),html.Div(id='page-2-content'),html.Br(),dcc.Link('Go to Pie Chart', href='/page-1'),html.Br(),dcc.Link('Go back to home', href='/')
])@callback(Output('page-2-content', 'children'),[Input('page-2-radios', 'value')])
def page_2_radios(value):return f'You have selected {value}'page_3_layout = html.Div([html.H1('Page 3'),dash_table.DataTable(df3.to_dict('records'), [{"name": i, "id": i} for i in df3.columns]),html.Div(id='page-3-content'),html.Br(),dcc.Link('Go to Line chart', href='/page-3'),html.Br(),dcc.Link('Go back to home', href='/'),
])@callback(Output('page-3-content', 'children'),[Input('page-3-dropdown', 'value')])
def page_3_dropdown(value):return f'You have selected {value}'# Update the index
@callback(Output('page-content', 'children'),[Input('url', 'pathname')])
def display_page(pathname):if pathname == '/page-1':return page_1_layoutelif pathname == '/page-2':return page_2_layoutelif pathname == '/page-3':return page_3_layoutelse:return index_page# You could also return a 404 "URL not found" page hereif __name__ == '__main__':app.run_server(debug=True)
# Here add all required functions. example.py
import pandas as pddef cost_function(df, dt=1, start='08:30:00', end='22:30:00', low_price=0.08, high_price=0.121):low1 = df.between_time('00:00:00', start)high = df.between_time(start, end)low2 = df.between_time(end, '23:59:59')# Calculate energy consumption(kWh) during different periodsenergy_low = (low1.Power.sum() + low2.Power.sum()) / (36 * 10 ** 5)energy_high = (high.Power.sum()) / (36 * 10 ** 5)cost_low = energy_low * low_pricecost_high = energy_high * high_pricecost = cost_low + cost_highreturn costdef read_example_csv():df = pd.read_csv('example_data.csv', sep=',', index_col=0, parse_dates=True)return dfdef state(current_power, threshold_dictionary={"off": [0, 200], "idle": [201, 500], "on": [501]}):off_upper_limit = threshold_dictionary.get("off")[1]idle_lower_limit = off_upper_limit + 1idle_upper_limit = threshold_dictionary.get("idle")[1]on_lower_limit = idle_upper_limit + 1if (current_power >= on_lower_limit):return "On"elif (current_power >= 201):return "Idle"else:return "Off"def current_power(df):latest_time_df = df.index.max().strftime('%Y-%m-%d %X')total_current_power = latest_time_df.Power.sum()return total_current_powerdef predict_cost(df):"""need to upate"""return cost_function(df)def summary(dataframe):total_energy = dataframe.Power.sumtotal_cost = cost_function(dataframe)instantaneous_power = current_power(dataframe)expected_cost = predict_cost(dataframe)data_dict = {"Total_Energy": total_energy, "Total_cost": total_cost, "Current_Power": instantaneous_power,"Expected_Cost": expected_cost}return data_dict

Notes from Python Dash

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m3aXUuD6-1644684167119)(…/…/Library/Application%20Support/typora-user-images/image-20220212163814079.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oQ6Y7J95-1644684167119)(…/…/Library/Application%20Support/typora-user-images/image-20220212163835117.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cQpw81KP-1644684167119)(…/…/Library/Application%20Support/typora-user-images/image-20220212163913676.png)]

pd.read_csv('file_name.csv', usecols= ['column_name1','column_name2'])
pd.read_csv(path_to_import,usecols=columns, sep=';').to_csv('selected.csv', index=False)
df.rename({'a': 'X', 'b': 'Y'}, axis=1, inplace=True)
dfX  Y  c  d  e
0  x  x  x  x  x
1  x  x  x  x  x
2  x  x  x  x  x

Functions.py

max(list)
import plotly.express as px
# This dataframe has 244 lines, but 4 distinct values for `day`
df = px.data.tips()
fig = px.pie(df, values='tip', names='day')
fig.show()
Date-Time,Power,Machine
12/02/2022 00:00:00,1321.08,robot1
12/02/2022 00:00:01,28354.84,robot1
12/02/2022 00:00:02,6677.94,robot1
12/02/2022 00:00:03,1598.42,robot1
12/02/2022 00:00:04,438.78,robot1
12/02/2022 00:00:05,296.18,robot1
12/02/2022 00:00:06,269.7,robot1
12/02/2022 00:00:07,160.68,robot1
12/02/2022 00:00:08,270.38,robot1
12/02/2022 00:00:09,274.82,robot1
12/02/2022 00:00:10,271.99,robot1
12/02/2022 00:00:11,273.28,robot1
12/02/2022 00:00:12,121.88,robot1
12/02/2022 00:00:13,261.44,robot1
12/02/2022 00:00:14,252.33,robot1

from dash import Dash, dcc, html, Input, Output
import plotly.express as px

import pandas as pd

df = pd.read_csv(‘https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv’)

app = Dash(name)

app.layout = html.Div([
dcc.Graph(id=‘graph-with-slider’),
dcc.Slider(
df[‘year’].min(),
df[‘year’].max(),
step=None,
value=df[‘year’].min(),
marks={str(year): str(year) for year in df[‘year’].unique()},
id=‘year-slider’
)
])

@app.callback(
Output(‘graph-with-slider’, ‘figure’),
Input(‘year-slider’, ‘value’))
def update_figure(selected_year):
filtered_df = df[df.year == selected_year]

fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",size="pop", color="continent", hover_name="country",log_x=True, size_max=55)fig.update_layout(transition_duration=500)return fig

if name == ‘main’:
app.run_server(debug=True)

from dash import Dash, dash_table
import pandas as pd

df = pd.read_csv(‘https://raw.githubusercontent.com/plotly/datasets/master/solar.csv’)

app = Dash(name)

app.layout = dash_table.DataTable(df.to_dict(‘records’), [{“name”: i, “id”: i} for i in df.columns])

if name == ‘main’:
app.run_server(debug=True)

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
dfcol1  col2
0     1     3
1     2     4

Visualization Document Feb 12 16:42相关推荐

  1. 顺丰同城:香港IPO发行价定为16.42港元

    12月13日消息,顺丰同城在港交所发布公告,发售价已定为每股16.42港元. 根据发售价16.42港元计,于扣除承销费用及本公司就全球发售应付的其他估计开支后,公司自全球发售收取的所得款项净额约为20 ...

  2. 股票交易日志4 12.16

    股票交易日志12.16 总资产:199613.48 当日参考盈亏:+597.00 买入:五粮液 23964.00/100/239.640 卖出:蓝色光标 1114.00/100/11.140,东方雨虹 ...

  3. 微软必应(Bing)打不开解决方案(2021.12.16)

    2021.12.19 0:10更新:现在Bing已修复,可直接通过https://cn.bing.com/访问~ 问题描述 2021.12.16开始必应就打不开了.. 解决方案 1. 打开主页 将原先 ...

  4. Feb. 27, 16:00-17:00, 1479, Energy-critical Schrodinger equations on manifolds by Sebastian Herr

    Title: Energy-critical Schrodinger equations on manifolds Speaker: Sebastian Herr (Univ. Bielefeld) ...

  5. 12.16 Daily Scrum

      Today's Task Tomorrow's Task 丁辛 实现和菜谱相关的餐厅列表. 实现和菜谱相关的餐厅列表.             邓亚梅             美化搜索框UI. 美 ...

  6. _signature、X-Bogus、msToken生成【2022.12.16】全站通用X-Bogus

    本文以教学为基准.本文提供的可操作性不得用于任何商业用途和违法违规场景. 本人对任何原因在使用本人中提供的代码和策略时可能对用户自己或他人造成的任何形式的损失和伤害不承担责任. 包含关注,点赞等 没露 ...

  7. 12.16库的相关知识与补充

    12.16 25.标准库:     (1)turtle库:Turtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x.纵轴为y的坐标系原点,(0,0)位置开始,它根 ...

  8. 谷歌Chrome超越苹果Safari 市场份额升至第三(每日关注2009.12.16)

     谷歌Chrome超越苹果Safari 市场份额升至第三  2009年12月16日消息,据国外媒体报道,调研公司NetApplications最新数据显示,在刚刚过去的一周,谷歌Chrome浏览器市场 ...

  9. 12.16直播:藏在华为物联网操作系统里的“秘密”

    华为物联网操作系统是啥?华为物联网操作系统和鸿蒙什么关系?用华为物联网的操作系统对我的设备有啥好处?我的设备想要上华为物联网平台,一定要用华为物联网的操作系统? -- 12月16日,有10年物联网从业 ...

最新文章

  1. SVN中update to revision与revert to revision的区别
  2. 音视频技术开发周刊 82期
  3. 【bzoj4712】洪水
  4. java 线程池 wait,Java 多线程 之 wait等待 线程实例
  5. react div 事件优先级_React 架构的演变 更新机制
  6. Axure经典案例高保真下载(智慧水务、智慧泵房、水厂监控、营收管理、DMA漏损、维护管理、档案管理、仓库管理、水质监控、数据中心、调度指挥中心)
  7. springmvc+mybatis多数据源配置,AOP注解动态切换数据源
  8. x5内核有什么优点_关于接入腾讯X5内核的一些坑(不断更新)
  9. Gallery3D简介
  10. 计算机名词解释高级筛选,高级筛选什么意思?
  11. 怎样学计算机打字最快,怎样学电脑快速打字
  12. chrome浏览器使用方法介绍
  13. 2022泰迪杯a题害虫检测
  14. Shiro的介绍与使用
  15. Raki的读paper小记:Image as a Foreign Language: BEIT Pretraining for All Vision and Vision-Language Tasks
  16. 【非数值数据的编码】西文字符和汉字的编码表示 汉字国标码、机内码详细理解
  17. 需求分析模板_人人都是视频大师:视频“拍摄编辑”功能分析
  18. Android系统静默安装预置应用宝
  19. 机器人视觉引导系统原理及解决方案
  20. 经济学原理-曼昆 学习笔记一

热门文章

  1. unity如何实现图片透视_如何用nginx实现防盗链?保护网站图片、视频。
  2. mysql用户数据导入_MySQL添加用户、删除用户与授权和数据的导入导出
  3. linux写程序四则运算,Shell编程之变量及四则运算
  4. redis常用API
  5. 项目质量管理:质量与质量管理概念
  6. SqlServerManagement新建数据库并执行sql文件流程
  7. Thymeleaaf中设置属性值实现动态控制select是否可选
  8. java炒黄金_炒黄金追单的一些问题分析
  9. git切换到旧版本_github上怎么切换到某次提交?
  10. 、简述global关键字的作用_详解static inline关键字