如何在绘图中通过循环添加多个形状

编程入门 行业动态 更新时间:2024-10-13 00:35:23
本文介绍了如何在绘图中通过循环添加多个形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用plotly包在python上显示动态财务图表.但是,我没有设法将所有关键点线放在带有for循环的一张图表上.这是我的代码:

fig.update_layout(对于范围(0,len(data))中的i:形状= [go.layout.Shape(输入="rect",x0 = data ['Date'] [i],y0 = data ['Max_alt'] [i],x1 ='2019-12-31',y1 = data ['Max_ust'] [i],fillcolor ="LightSkyBlue",不透明度= 0.5,layer ="below",line_width = 0)])图show()

我有一个类似下面的数据.它是基于时间序列的EURUSD平价金融数据集.我为本地最小"和最大"计算了两个等式.我想根据每个Min_alt/Min_ust和Max_alt/Max_range绘制矩形形状.我只能像下图那样绘制一个日期,但是我没有设法在同一个绘图图中显示所有范围.

这是

以下是添加行的解决方案:

导入日期时间颜色= ["LightSkyBlue","RoyalBlue","forestgreen","lightseagreen"]ply_shapes = {}对于范围(0,len(data1))中的i:ply_shapes ['shape_'+ str(i)] = go.layout.Shape(type ="rect",x0 = data1 ['Date'] [i] .strftime('%Y-%m-%d'),y0 = data1 ['Max_alt'] [i],x1 ='2019-12-31',y1 = data1 ['Max_ust'] [i],fillcolor ="LightSkyBlue",不透明度= 0.5,layer ="below")lst_shapes = list(ply_shapes.values())fig1.update_layout(shapes = lst_shapes)fig1.show()

但是我仍然难以在这些行上添加跟踪.我的意思是文字属性.

这是我的代码:

add_trace = {}对于范围(0,len(data1))中的i:add_trace ['scatter_'+ str(i)] = go.Scatter(x = ['2019-12-31'],y = [data1 ['Max_ust'] [i]],text = [str(data ['Max_Label'] [i])],mode ="text")lst_trace =列表(add_trace.values())fig2 = go.Figure(lst_trace)fig2.show()

解决方案

答案:

要完全控制要插入的每个形状,可以遵循以下逻辑:

fig = go.Figure()#[...]数据,痕迹等ply_shapes = {}对于范围(1,len(df))中的i:ply_shapes ['shape_'+ str(i)] = go.layout.Shape()lst_shapes = list(ply_shapes.values())fig.update_layout(shapes = lst_shapes)图show()

详细信息:

我不确定您打算在这里做什么,但是下面的建议可以从字面上回答您有关以下问题的确切建议:

如何在绘图中添加多个带有循环的形状?

然后,您必须弄清楚有关以下内容的详细信息:

将所有关键点线放在一张图表上

情节:

该图本身很可能不是您要查找的,但是由于某种原因,由于您要根据数据的长度添加一个图,因此范围为(0,len(data),我做到了:

代码:

此代码段将显示如何使用for循环处理所有所需的迹线和形状:

#导入将熊猫作为pd导入#将matplotlib.pyplot导入为plt将numpy导入为np随地导入plotly.graph_objects#from plotly.offline导入download_plotlyjs,init_notebook_mode,plot,iplot#数据,随机样本说明股票np.random.seed(12345)行= 20x = pd.Series(np.random.randn(行),index = pd.date_range('1/1/2020',周期=行)).cumsum()y = pd.Series(x-np.random.randn(rows)* 5,index = pd.date_range('1/1/2020',period = rows))df = pd.concat([y,x],轴= 1)df.columns = ['StockA','StockB']#行df ['keyPoints1'] = np.random.randint(-5,5,len(df))df ['keyPoints2'] = df ['keyPoints1'] *-1#绘图痕迹无花果= go.Figure()股票= ['StockA','StockB']df [stocks] .tail()痕迹= {}对于i在范围(0,len(stock))中:traces ['trace_'+ str(i)] = go.Scatter(x = df.index,y = df [stocks [i]].values,名称=股票[i])数据=列表(traces.values())fig = go.Figure(数据)#形状更新颜色= ["LightSkyBlue","RoyalBlue","forestgreen","lightseagreen"]ply_shapes = {}对于范围(1,len(df))中的i:ply_shapes ['shape_'+ str(i)] = go.layout.Shape(type ="line",x0 = df.index [i-1],y0 = df ['keyPoints1'].iloc [i-1],x1 = df.index [i],y1 = df ['keyPoints2'].iloc [i-1],线=字典(color = np.random.choice(colors,1)[0],宽度= 30),不透明度= 0.5,layer ="below")lst_shapes = list(ply_shapes.values())fig.update_layout(shapes = lst_shapes)图show()

I use plotly package to show dynamic finance chart at python. However I didn't manage to put my all key points lines on one chart with for loop. Here is my code:

fig.update_layout( for i in range(0,len(data)): shapes=[ go.layout.Shape( type="rect", x0=data['Date'][i], y0=data['Max_alt'][i], x1='2019-12-31', y1=data['Max_ust'][i], fillcolor="LightSkyBlue", opacity=0.5, layer="below", line_width=0)]) fig.show()

I have a data like below one. It is time series based EURUSD parity financial dataset. I calculated two constraits for both Local Min and Max. I wanted to draw rectangule shape to based on for each Min_alt / Min_ust and Max_alt / Max_range. I can draw for just one date like below image however I didn't manage to show all ranges in same plotly graph.

Here is the sample data set.

Here is the solution for added lines:

import datetime colors = ["LightSkyBlue", "RoyalBlue", "forestgreen", "lightseagreen"] ply_shapes = {} for i in range(0, len(data1)): ply_shapes['shape_' + str(i)]=go.layout.Shape(type="rect", x0=data1['Date'][i].strftime('%Y-%m-%d'), y0=data1['Max_alt'][i], x1='2019-12-31', y1=data1['Max_ust'][i], fillcolor="LightSkyBlue", opacity=0.5, layer="below" ) lst_shapes=list(ply_shapes.values()) fig1.update_layout(shapes=lst_shapes) fig1.show()

However I have still problems to add traces to those lines. I mean text attribute.

Here is my code:

add_trace = {} for i in range(0, len(data1)): add_trace['scatter_' + str(i)] = go.Scatter( x=['2019-12-31'], y=[data1['Max_ust'][i]], text=[str(data['Max_Label'][i])], mode="text") lst_trace = list(add_trace.values()) fig2=go.Figure(lst_trace) fig2.show()

解决方案

The answer:

For full control of each and every shape you insert, you could follow this logic:

fig = go.Figure() #[...] data, traces and such ply_shapes = {} for i in range(1, len(df)): ply_shapes['shape_' + str(i)]=go.layout.Shape() lst_shapes=list(ply_shapes.values()) fig.update_layout(shapes=lst_shapes) fig.show()

The details:

I'm not 100% sure what you're aimin to do here, but the following suggestion will answer your question quite literally regarding:

How to add more than one shape with loop in plotly?

Then you'll have to figure out the details regarding:

manage to put my all key points lines on one chart

Plot:

The plot itself is most likely not what you're looking for, but since you for some reason are adding a plot by the length of your data for i in range(0,len(data), I've made this:

Code:

This snippet will show how to handle all desired traces and shapes with for loops:

# Imports import pandas as pd #import matplotlib.pyplot as plt import numpy as np import plotly.graph_objects as go #from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot # data, random sample to illustrate stocks np.random.seed(12345) rows = 20 x = pd.Series(np.random.randn(rows),index=pd.date_range('1/1/2020', periods=rows)).cumsum() y = pd.Series(x-np.random.randn(rows)*5,index=pd.date_range('1/1/2020', periods=rows)) df = pd.concat([y,x], axis = 1) df.columns = ['StockA', 'StockB'] # lines df['keyPoints1']=np.random.randint(-5,5,len(df)) df['keyPoints2']=df['keyPoints1']*-1 # plotly traces fig = go.Figure() stocks = ['StockA', 'StockB'] df[stocks].tail() traces = {} for i in range(0, len(stocks)): traces['trace_' + str(i)]=go.Scatter(x=df.index, y=df[stocks[i]].values, name=stocks[i]) data=list(traces.values()) fig=go.Figure(data) # shapes update colors = ["LightSkyBlue", "RoyalBlue", "forestgreen", "lightseagreen"] ply_shapes = {} for i in range(1, len(df)): ply_shapes['shape_' + str(i)]=go.layout.Shape(type="line", x0=df.index[i-1], y0=df['keyPoints1'].iloc[i-1], x1=df.index[i], y1=df['keyPoints2'].iloc[i-1], line=dict( color=np.random.choice(colors,1)[0], width=30), opacity=0.5, layer="below" ) lst_shapes=list(ply_shapes.values()) fig.update_layout(shapes=lst_shapes) fig.show()

更多推荐

如何在绘图中通过循环添加多个形状

本文发布于:2023-10-28 04:54:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535579.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   形状   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!