Plotly Express,如何使用for_each_trace

标签 plotly

谁能帮我解决这个问题。我正在尝试在绘制 px.bar 图中的所有负条时为其着色。我正在研究如何访问每个单独条形的 y 值,我正在将所有内容绘制为绿色,并且我想返回并将负条形着色为红色。日期必须保持顺序。这是我正在尝试的

这是我的数据框

     DATE  Profit/Loss Marker  Cumulative_PnL  Daily_Volume  WinRate 
 08/16/21     -58.1995    red        -58.1995      604.0000  80.0000         
 08/17/21      -4.7700    red        -62.9695        4.0000  50.0000        
 08/18/21      31.4984  green        -31.4711     1908.0000 100.0000      
 08/20/21      49.6200  green         18.1489     1006.0000  50.0000       
 08/23/21    -930.1800    red       -912.0311      712.0000  50.0000        
 08/24/21      99.1000  green       -812.9311      306.0000 100.0000         
 08/25/21      -0.6400    red       -813.5711      332.0000  60.0000        
 08/26/21     -50.0300    red       -863.6011     2556.0000  66.6667        
 08/27/21      -9.9100    red       -873.5111       38.0000  81.8182         
 08/30/21       7.8500  green       -865.6611      424.0000  91.6667        
 08/31/21       1.0000  green       -864.6611       40.0000 100.0000      
 09/01/21    -367.9500    red      -1232.6111      981.0000  76.9231         
 09/02/21     178.9900  green      -1053.6211      308.0000  71.4286        
 09/03/21     -32.1000    red      -1085.7211      928.0000  62.5000

fig1.for_each_trace(lambda trace: trace.update(marker_color= 'red') if trace.y < 0 else (),) 

enter image description here

最佳答案

  • 您尚未提供所有跟踪的示例数据,因此我生成了一个数据框
  • 直接调用 px.bar() 我循环遍历轨迹,将 +ve Y 值设置为黑色,并在创建条形时使用指定的颜色
  • 关键是根据需要的更改更新图中的跟踪
import plotly.express as px
import pandas as pd
import numpy as np

ROWS = 20
LINES = 5

# construct a dataset to use plotly express with multiple traces
df = (
    pd.wide_to_long(
        pd.DataFrame(
            np.random.uniform(-10, 3, (ROWS, LINES)),
            columns=[f"Y{n}" for n in range(LINES)],
        ).reset_index(),
        i="index",
        j="color",
        stubnames="Y",
    )
    .reset_index()
    .assign(color=lambda d: d["color"].astype(str))
)

fig = px.bar(df, x="index", y="Y", color="color", barmode="group")

# in each trace, set all positive numbers to black and negative numbers use trace color
for t in fig.data:
    fig.update_traces(marker={"color": np.where(t.y>0, "black", t.marker.color)}, selector={"name":t.name})

fig.show()

enter image description here

关于Plotly Express,如何使用for_each_trace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69507154/

相关文章:

R + plotly : solid of revolution

python - Plotly:如何使用下拉菜单在每日和每小时烛台之间进行更改?

animation - 如何导出/保存用 plotly 制作的动画气泡图?

python - 使用 Python 离线更新图表

python - 在python中绘制带有图例的垂直线

plotly - Plotly 的默认色标是什么?

r - HTML 希腊字母与 ggplotly

python - Plotly:如何添加多个 y 轴?

javascript - 是否可以在plot.ly 3D散点图上手动设置比例和刻度?

R绘图(): Adding regression line to a correlation scatter plot