英文:
Set plotly bargap to 0
问题
抱歉,我只提供中文翻译,不回答代码相关的问题。以下是代码的中文翻译:
我无法将Plotly的bargap设置为0(使用datetime作为x轴)
以下是代码:
import pandas as pd
import numpy as np
import plotly
print (plotly.__version__)
# 创建一个包含一年中每个月第一天日期的列表
df = pd.DataFrame({
"month": pd.date_range(start='2021-01-01', end='2022-08-01', freq='MS'),
"count": np.random.randint(0, 11, size=20)
})
import plotly.express as px
fig = px.bar(df, x='month', y='count')
fig.update_layout(width=1200, height=400, bargap=0)
fig.update_layout(xaxis_rangeslider_visible=False)
fig.update_xaxes(
dtick="M1",
tickformat="%b\n%Y")
fig.show()
英文:
I am unable to set the plotly bargap to 0 (am using datetime for x axis)
here is the code:
import pandas as pd
import numpy as np
import plotly
print (plotly.__version__)
# Create a list of dates for the first day of each month in a year
df = pd.DataFrame({
"month": pd.date_range(start='2021-01-01', end='2022-08-01', freq='MS'),
"count": np.random.randint(0, 11, size=20)
})
import plotly.express as px
fig = px.bar(df, x='month', y='count')
fig.update_layout(width=1200, height=400, bargap=0)
fig.update_layout(xaxis_rangeslider_visible=False)
fig.update_xaxes(
dtick="M1",
tickformat="%b\n%Y")
fig.show()
答案1
得分: 1
你需要将month
列从日期转换为对象类型:
df.month = df.month.dt.strftime('%b-%Y')
英文:
You need to convert the month
column from date to object type:
import pandas as pd
import numpy as np
import plotly
import plotly.express as px
df = pd.DataFrame({
"month": pd.date_range(start='2021-01-01', end='2022-08-01', freq='MS'),
"count": np.random.randint(0, 11, size=20)
})
df.month = df.month.dt.strftime('%b-%Y')
fig = px.bar(df, x='month', y='count')
fig.update_layout(bargap=0)
fig.show()
Output:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论