【问题标题】:how to add a constant line to hvplot如何在 hvplot 中添加一条恒定线
【发布时间】:2020-03-05 12:19:17
【问题描述】:

如何在 hvplot 中添加水平线? Holoviews 有 .HLine 和 .VLine 但不知道如何通过 pandas.hvplot 或 hvplot 访问它

这是一个示例数据框和绘图脚本。

import pandas as pd
import hvplot.pandas

df = pd.DataFrame({'A':[100], 'B':[20]})
df = df.reset_index()

print(df)
#   index   A       B
#0  0       100     20

# create plot
plot = df.hvplot.bar(y=['A', 'B'], x='index', 
              rot=0, subplots=False, stacked=True)

plot


【问题讨论】:

    标签: python pandas holoviews hvplot


    【解决方案1】:

    我会像这样覆盖全息视图hv.HLine() 到您的情节:

    import holoviews as hv
    
    your_hvplot * hv.HLine(60)
    

    在代码中使用 * 符号 可以轻松地将 HLine 置于其他绘图之上。
    这称为Overlay


    如果您还需要带有 HLine 的标签,此 SO 问题包含一个示例:
    How do I get a full-height vertical line with a legend label in holoviews + bokeh?


    您的示例代码与水平线将如下所示:

    # import libraries
    import pandas as pd
    import hvplot.pandas
    import holoviews as hv
    
    # sample data
    df = pd.DataFrame({'A':[100], 'B':[20]})
    
    # create plot
    plot = df.hvplot.bar(
        y=['A', 'B'], 
        stacked=True, 
        xaxis='', 
        title='Adding horizontal line hv.HLine() to plot with * overlay',
    )
    
    # create separate hline 
    # for demonstration purposes I added some styling options
    hline = hv.HLine(60)
    hline.opts(
        color='red', 
        line_dash='dashed', 
        line_width=2.0,
    )
    
    # add hline to plot using * which overlays the hline on the plot
    plot * hline
    

    最终结果:

    【讨论】:

    • 感谢您展示了如何避免使用“索引”,那是丑陋的 hack。
    • 是的,在这种情况下,如果您不指定“x”参数,hvplot() 将自动将数据框的索引作为“x”参数。但有时我也发现自己在 .reset_index() 不起作用的情况下使用它:)
    猜你喜欢
    • 2019-04-25
    • 2018-08-09
    • 2020-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多