[英]Succint way to add line segments to plotly graph (with python/jupyter notebook)?
我想用幾個這樣的水平線段創建一個棒棒糖圖 -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-相對於軸定位),但是這兩種解決方案都需要單獨添加每個線段,每個線段大約有 4-8 行代碼。 雖然我可以只循環這個,但如果有人能指出我任何帶有內置矢量化的東西,比如 matplotlib 解決方案(第一個鏈接),我將不勝感激!
編輯:還嘗試了以下代碼,首先使繪圖 ala matplotlib,然后轉換為繪圖。 線段在此過程中消失。 開始覺得這不可能。
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)
Plotly 不為此類圖表提供內置矢量化,因為您可以輕松完成,請根據您提供的鏈接查看我的示例:
import pandas as pd
import numpy as np
import plotly.offline as pyo
import plotly.graph_objs as go
# Create a dataframe
value1 = np.random.uniform(size = 20)
value2 = value1 + np.random.uniform(size = 20) / 4
df = pd.DataFrame({'group':list(map(chr, range(65, 85))), 'value1':value1 , 'value2':value2 })
my_range=range(1,len(df.index)+1)
# Add title and axis names
data1 = go.Scatter(
x=df['value1'],
y=np.array(my_range),
mode='markers',
marker=dict(color='blue')
)
data2 = go.Scatter(
x=df['value2'],
y=np.array(my_range),
mode='markers',
marker=dict(color='green')
)
# Horizontal line shape
shapes=[dict(
type='line',
x0 = df['value1'].loc[i],
y0 = i + 1,
x1 = df['value2'].loc[i],
y1 = i + 1,
line = dict(
color = 'grey',
width = 2
)
) for i in range(len(df['value1']))]
layout = go.Layout(
shapes = shapes,
title='Lollipop Chart'
)
# Plot the chart
fig = go.Figure([data1, data2], layout)
pyo.plot(fig)
結果我得到了:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.