gpt4 book ai didi

python - Plotly 多类别 X 轴排序

转载 作者:行者123 更新时间:2023-12-05 07:01:41 24 4
gpt4 key购买 nike

我正在尝试创建一个带日期的多类别 x 轴,下面的代码和图表为我提供了我想要的外观,但它只是乱序。我试过使用“原始 x 轴”列而不是月份,但格式显示不正确,我似乎无法更改它的格式。

import random
import numpy as np
import plotly.express as px

df = pd.DataFrame({"Year":np.repeat([2018,2019],[8,12]),
"Month": ["May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"Original x-axis": pd.date_range(start = "2018-05-01", end = "2019-12-01", freq = "MS"),
"Customer Satisfaction Score": random.sample(range(30,100), 20)})


fig = go.Figure()

fig.add_trace(go.Scatter(
#x = cust["Original x-axis"],
x = [df["Year"],df["Month"]],
y = df["Customer Satisfaction Score"], mode = "lines"))

fig.update_layout(plot_bgcolor = "white",
annotations = [dict(text = "Customer Satisfaction Score",
yref = "paper",
xref = "paper",
x = 0,
y = 1.1,
font = dict(size = 16, color = "#909497"),
showarrow = False)],
font = dict(size = 12, color = "#BDC3C7"))
#xaxis = dict(tickformat = "%b"))

fig.show()

enter image description here

最佳答案

请检查代码段。您需要根据 对日期时间列进行排序。

在这里我为此创建了一个额外的列。其余部分相同。

df['month'] = df['Original x-axis'].dt.strftime('%b-%Y')

PLOT

import random
import numpy as np
import plotly.express as px
import pandas as pd
import plotly.offline as py
import plotly.graph_objs as go
df = pd.DataFrame({"Year":np.repeat([2018,2019],[8,12]),
"Month": ["May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
"Original x-axis": pd.date_range(start = "2018-05-01", end = "2019-12-01", freq = "MS"),
"Customer Satisfaction Score": random.sample(range(30,100), 20)})

df['month'] = df['Original x-axis'].dt.strftime('%b-%Y')
fig = go.Figure()

fig.add_trace(go.Scatter(
#x = cust["Original x-axis"],
x = [df["Year"],df["month"]],
y = df["Customer Satisfaction Score"], mode = "lines"))

fig.update_layout(plot_bgcolor = "white",
annotations = [dict(text = "Customer Satisfaction Score",
yref = "paper",
xref = "paper",
x = 0,
y = 1.1,
font = dict(size = 16, color = "#909497"),
showarrow = False)],
font = dict(size = 12, color = "#BDC3C7"))
#xaxis = dict(tickformat = "%b"))

fig.show()

关于python - Plotly 多类别 X 轴排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63772298/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com