Adding group bar charts as subplots in plotly

此生再无相见时 提交于 2019-12-08 16:15:12

问题


I want to create grouped (barmode='group') bar chart subplots in plotly. Now the problem is that plotly doesn't create bar charts as traces. Instead grouped bar charts are created as lists of Bar traces. Because of this, I don't know how to create a figure that contains grouped bar charts as subplots (i.e. add a grouped bar chart using figure.append_trace()).

For example, how can I create subplots using bar charts created in 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')

回答1:


YES! New to plot.ly and had this issue, and as mentioned in my comment, I couldn't just do it in pandas/matplotlib for various reasons. But through the magic of subplots, you can in fact recreate multi-trace plots by just subploting them together.

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)



回答2:


I've never used the plotly package but what it seems you are after is fairly straightforward using matplotlib. Here is a pretty minimal example of showing grouped bar charts as a subplot. Let me know if this is not quite what you were asking for.

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()



来源:https://stackoverflow.com/questions/37033581/adding-group-bar-charts-as-subplots-in-plotly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!