Python将瀑布图转换为plotly

2024-04-29 13:42:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python中的waterfall_chart包来创建瀑布图。这个包主要在后端使用matplotlib,所以我试图使用tls.mpl_to_plotly(mpl_fig)函数将matplotlib图形转换为plotly。但是转换时,会弹出一个错误。有没有一种方法可以将waterfall_chart转换成{},或者有没有一种简单的方法直接在plotly中创建图表?我在plotly中看到了一些关于类似的chart的讨论,但是它涉及到相当手工的图表编号编码。在

您可以使用以下代码重新创建图表。在

import waterfall_chart
import matplotlib.pyplot as plt
import plotly.tools as tls

a = ['sales','returns','credit fees','rebates','late charges','shipping']
b = [10,-30,-7.5,-25,95,-7]
mpl_fig = plt.figure()
waterfall_chart.plot(a, b)

plt.show()

waterfall chart

但是当我试图使用mpl_to_plotly()转换为plotly时,出现了一个错误:

^{pr2}$

waterfall_chart包的详细信息可以在这里找到:https://github.com/chrispaulca/waterfall/blob/master/waterfall_chart.py


Tags: to方法importmatplotlibas错误chart图表
1条回答
网友
1楼 · 发布于 2024-04-29 13:42:29

我的答案是

[...] or is there an easy way to create the chart directly in plotly?


对于plotly的更新版本,您可以使用plotly.graph_objs.Waterfall

下面是一个基本示例,其中包含一个在脱机Jupyter笔记本中使用iplot的设置的数据示例:

绘图:

enter image description here

代码:

# imports
import plotly
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
from IPython.core.display import display, HTML
import plotly.figure_factory as ff
import plotly.graph_objs as go
import pandas as pd
import numpy as np

# setup
display(HTML("<style>.container { width:35% !important; } .widget-select > select {background-color: gainsboro;}</style>"))
init_notebook_mode(connected=True)
np.random.seed(1)

import plotly.offline as py
import plotly.graph_objs as go
py.init_notebook_mode(connected = False)

# your values
a = ['sales','returns','credit fees','rebates','late charges','shipping']
b = [10,-30,-7.5,-25,95,-7]

# waterfall trace
trace = go.Waterfall(
     x = a, 
    textposition = "outside", 
    text = [str(elem) for elem in b], 
    y = b, 
    connector = {"line":{"color":"rgb(63, 63, 63)"}}, 
)

layout = go.Layout(
        title = "Waterfall chart, plotly version 3.9.0", 
        showlegend = True
)

iplot(go.Figure([trace], layout))

检查您的版本:

^{pr2}$

使用以下命令在cmd控制台中更新您的版本:

pip install plotly  upgrade

相关问题 更多 >