[英]Plotly Multicategory X Axis Ordering
I'm trying to create a multi category x axis with dates, the below code & graph gives me what I want it terms of how it looks but it's just out of order.我正在尝试创建一个带有日期的多类别 x 轴,下面的代码和图表为我提供了我想要的外观,但它只是乱序。 I've tried using the 'Original x-axis' column instead of month but then the format doesn't appear correctly and I can't seem to change the format of it.我尝试使用“原始 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()
Please check the snippet.请检查代码段。 You need to sort your date_time column based on year as well as month .您需要根据year和month对 date_time 列进行排序。
Here I created an extra column for that.在这里,我为此创建了一个额外的列。 Rest all the part is same.其余部分相同。
df['month'] = df['Original x-axis'].dt.strftime('%b-%Y')
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.