Set plotly bargap to 0.

huangapple go评论73阅读模式
英文:

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

Set plotly bargap to 0.

英文:

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

Set plotly bargap to 0.

答案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:

Set plotly bargap to 0.

huangapple
  • 本文由 发表于 2023年3月7日 01:01:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75653720.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定