gpt4 book ai didi

python - 将线段添加到绘图的简洁方法(使用 python/jupyter notebook)?

转载 作者:行者123 更新时间:2023-11-28 18:57:59 25 4
gpt4 key购买 nike

我想创建一个带有多个水平线段的 Lollipop 图 - https://python-graph-gallery.com/184-lollipop-plot-with-2-group .我想使用 plotly,因为我更喜欢图形(和简单的交互性),但找不到简洁的方法。

既有折线图 (https://plot.ly/python/line-charts/),也可以在布局中添加线条 (https://plot.ly/python/shapes/#vertical-and-horizontal-lines-positioned-relative-to-the-axes),但这两种解决方案都需要单独添加每个线段,每个线段大约有 4-8 行代码。虽然我可以对此进行循环,但如果有人能指出任何具有内置矢量化的东西,比如 matplotlib 解决方案(第一个链接),我将不胜感激!

编辑:还尝试了以下代码,首先使绘图成为 matplotlib,然后转换为 plotly。线段在此过程中消失。开始认为这是不可能的。

mpl_fig = plt.figure()

# make matplotlib plot - WITH HLINES
plt.rcParams['figure.figsize'] = [5,5]
ax = mpl_fig.add_subplot(111)
ax.hlines(y=my_range, xmin=ordered_df['value1'], xmax=ordered_df['value2'],
color='grey', alpha=0.4)
ax.scatter(ordered_df['value1'], my_range, color='skyblue', alpha=1,
label='value1')
ax.scatter(ordered_df['value2'], my_range, color='green', alpha=0.4 ,
label='value2')
ax.legend()

# convert to plotly
plotly_fig = tls.mpl_to_plotly(mpl_fig)
plotly_fig['layout']['xaxis1']['showgrid'] = True
plotly_fig['layout']['xaxis1']['autorange'] = True
plotly_fig['layout']['yaxis1']['showgrid'] = True
plotly_fig['layout']['yaxis1']['autorange'] = True

# plot: hlines disappear :/
iplot(plotly_fig)

最佳答案

您可以像这样在数据中使用None:

import plotly.offline as pyo
import plotly.graph_objs as go

fig = go.Figure()

x = [1, 4, None, 2, 3, None, 3, 4]
y = [0, 0, None, 1, 1, None, 2, 2]

fig.add_trace(
go.Scatter(x=x, y=y))

pyo.plot(fig)

enter image description here

关于python - 将线段添加到绘图的简洁方法(使用 python/jupyter notebook)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55939775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com