我需要更改堆叠的条形图宽度以使其重叠。 我找到了这个问题和解决方案How to plot a superimposed bar chart using matplotlib in python?,我想在DASH Plotly python框架上重现相同的图表。
代码如下:
import matplotlib.pyplot as plt
import numpy as np
width = 0.8
highPower = [1184.53,1523.48,1521.05,1517.88,1519.88,1414.98,
1419.34,1415.13,1182.70,1165.17]
lowPower = [1000.95,1233.37, 1198.97,1198.01,1214.29,1130.86,
1138.70,1104.12,1012.95,1000.36]
indices = np.arange(len(highPower))
plt.bar(indices, highPower, width=width,
color='b', label='Max Power in mW')
plt.bar([i+0.25*width for i in indices], lowPower,
width=0.5*width, color='r', alpha=0.5, label='Min Power in mW')
plt.xticks(indices+width/2.,
['T{}'.format(i) for i in range(len(highPower))] )
plt.legend()
plt.show()
问题:如何进行编辑以适应DASH原则? 例如,在Dash上,bar不接受width = 0.5 * width和alpha = 0.5 谢谢。
我自己的代码如下:
from plotly.offline import init_notebook_mode, iplot
from plotly import graph_objs as go
init_notebook_mode(connected = True)
import pandas as pd
import numpy as np
dfb=pd.read_csv('https://www.dropbox.com/s/90y07129zn351z9/test_data.csv?dl=1', encoding="latin-1", infer_datetime_format=True, parse_dates=['date'], skipinitialspace=True)
dfb["date"]=pd.to_datetime(dfb['date'])
dfb["site"]=dfb["site"].astype("category")
cm_inc=dfb[dfb.site == 5].pivot_table(index='date', values = 'site', aggfunc = { 'site' : 'count' } )
dfb['cm_target'] = [40]*len(dfb)
dfb.to_csv('test_data.csv', index=False)
data = [
go.Bar(x=cm_inc.index, y=cm_inc['site'], name='Enroll Site A',
#base=0
),
go.Bar(x=cm_inc.index, y=dfb['cm_target'], name='Target Site A',
#base=0,
#width=0.5
)]
layout = go.Layout(
barmode='stack',
)
fig = dict(data = data, layout = layout)
iplot(fig, show_link=False)
@Teoretic提出的在两条迹线上都使用base = 0并使用barmode ='stack'的建议解决方案不起作用。 谢谢。
答案 0 :(得分:1)
编辑已编辑答案,以使用添加到问题中的新数据
您可以通过以下两个步骤在Plotly中进行重叠的条形图:
1)将布局中的barmode设置为“ stack”
2)将每个条形图的基数设置为0
3)小数值设置为X值
另外,您可能还想玩:
1)将第二个条形图的“宽度”参数设置为适合您的值
2)使“ X”轴数据的标签更适合您
示例代码(在Jupyter Notebook中运行):
from plotly.offline import init_notebook_mode, iplot
from plotly import graph_objs as go
init_notebook_mode(connected = True)
import pandas as pd
import numpy as np
dfb=pd.read_csv('https://www.dropbox.com/s/90y07129zn351z9/test_data.csv?dl=1', encoding="latin-1", infer_datetime_format=True, parse_dates=['date'], skipinitialspace=True)
dfb["date"]=pd.to_datetime(dfb['date'])
dfb["site"]=dfb["site"].astype("category")
cm_inc=dfb[dfb.site == 5].pivot_table(index='date', values = 'site', aggfunc = { 'site' : 'count' } )
dfb['cm_target'] = [40]*len(dfb)
dfb.to_csv('test_data.csv', index=False)
# You need small int indexes for "width" and "base" = 0 trick to work
indexes = [int(i.timestamp()) / 10000 for i in cm_inc.index]
# For string dates labels
dates_indexes = [str(i) for i in cm_inc.index]
data = [
go.Bar(x=indexes,
y=dfb['cm_target'],
name='Target Site A',
base=0
),
go.Bar(x=indexes,
y=cm_inc['site'],
name='Enroll Site A',
base=0,
width=5 # Width value varies depending on number of samples in data
)
]
layout = go.Layout(
barmode='stack',
xaxis=dict(
showticklabels=True,
ticktext=dates_indexes,
tickvals=[i for i in indexes],
)
)
fig = dict(data = data, layout = layout)
iplot(fig, show_link=False)
答案 1 :(得分:0)
from plotly.offline import init_notebook_mode, iplot
from plotly import graph_objs as go
init_notebook_mode(connected = True)
import pandas as pd
import numpy as np
from datetime import timedelta, datetime, tzinfo
import time
from datetime import datetime as dt
dfb=pd.read_csv('https://www.dropbox.com/s/90y07129zn351z9/test_data.csv?dl=1', encoding="latin-1", infer_datetime_format=True, parse_dates=['date'], skipinitialspace=True)
dfb["date"]=pd.to_datetime(dfb['date'])
dfb["site"]=dfb["site"].astype("category")
cm_inc=dfb[dfb.site == 5].pivot_table(index='date', values = 'site', aggfunc = { 'site' : 'count' } )
dfb['cm_target'] = [40]*len(dfb)
dfb.to_csv('test_data.csv', index=False)
# You need small int indexes for "width" and "base" = 0 trick to work
#indexes = [int(i.timestamp()) / 10000 for i in cm_inc.index]
indexes =pd.to_datetime(cm_inc.index)
# For string dates labels
#dates_indexes = [str(i) for i in cm_inc.index]
dates_indexes = pd.to_datetime(cm_inc.index)
data = [
go.Bar(x=indexes,
y=dfb['cm_target'],
name='Target Site A',
base=0
),
go.Bar(x=indexes,
y=cm_inc['site'],
name='Enroll Site A',
base=0,
#width=2 # Width value varies depending on number of samples in data
)
]
layout = go.Layout(
barmode='stack',
xaxis=dict(
showticklabels=True,
ticktext=dates_indexes,
tickvals=[i for i in indexes],
)
)
fig = dict(data = data, layout = layout)
iplot(fig, show_link=False)