在绘图中添加组条形图作为子图

2024-07-05 14:05:06 发布

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

我想以绘图方式创建分组(barmode='group')条形图子图。现在的问题是plotly没有创建条形图作为轨迹。相反,分组条形图被创建为条形图跟踪的列表。因此,我不知道如何创建包含分组条形图作为子图的图形(即使用figure.append_跟踪())。在

例如,如何使用在this sample中创建的条形图创建子批次: 在

import plotly.plotly as py
import plotly.graph_objs as go
trace1 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[20, 14, 23],
    name='SF Zoo'
)
trace2 = go.Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[12, 18, 29],
    name='LA Zoo'
)
data = [trace1, trace2]
layout = go.Layout(
    barmode='group'
)
fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='grouped-bar')

Tags: pyimportgodataasgroupbarplotly
2条回答

我从来没有使用过plotly包,但是使用matplotlib似乎很简单。下面是一个将分组条形图显示为子图的非常小的示例。如果这不是你想要的,请告诉我。在

import numpy as np
import matplotlib.pyplot as plt

# First subplot
plt.subplot(2, 1, 1)

x = np.linspace(0, 10)
y = np.sin(np.pi * x)

plt.plot(x, y)

# Second subplot
plt.subplot(2, 1, 2)
titles = ('Canada', 'US', 'England', 'Other')
y_pos = np.arange(len(titles))
width = 0.2
bar_height1 = [6,5,7,2]
bar_height2 = [x+1 for x in bar_height1]

plt.bar(y_pos, bar_height1, width, align='center', alpha=0.8, color='r')
plt.bar(y_pos+width, bar_height2, width, align='center', alpha=0.8, color='b')

plt.xticks(y_pos + width/2, titles)

# Show the plots
plt.show()

Matplotlib plot

是的!新手plot.ly公司有了这个问题,正如我在评论中提到的,出于各种原因,我不能仅仅在pandas/matplotlib中这样做。但是通过子图的魔力,你实际上可以通过将它们分块在一起来重新创建多轨迹图。 enter image description here

import plotly.plotly as py
import plotly.graph_objs as go
from plotly import tools

trace1 = Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[20, 14, 23],
    name='SF Zoo'
)
trace2 = Bar(
    x=['giraffes', 'orangutans', 'monkeys'],
    y=[12, 18, 29],
    name='LA Zoo'
)
trace3 = Scatter(
  x=['giraffes', 'orangutans', 'monkeys']
  ,y=[33,20,17]
  ,name='subplots ftw'
  )


fig = tools.make_subplots(rows=2, cols=1, shared_xaxes=True)

fig.append_trace(trace3, 1,1)
fig.append_trace(trace1, 2, 1)
fig.append_trace(trace2,2,1)


fig['layout'].update(height=600, width=600)
iplot(fig)

相关问题 更多 >