Plotly:如何更改xaxis上的默认日期并从axis中删除年份?

2024-09-26 22:13:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过plotly创建一个线图。我遇到了两个问题。Plotly默认显示x轴上的每7个值,并显示我的第一个x轴值的年份值(如屏幕截图所示)。下面是正在运行的代码。如果其中任何一个可以修复,那就太好了

from connect_to_db import get_df
import plotly.express as px
import os

df = get_df()

fig = px.bar(df, x='Date', y='Total', color='CUSTOMER_TYPE',
             color_discrete_sequence=["#E15759","#8CD17D"],  width=800, height=400)

fig.update_layout({'plot_bgcolor': 'rgba(0, 0, 0, 0)', 'paper_bgcolor': 'rgba(0, 0, 0, 0)', })

fig.update_layout(
    legend=dict(
        orientation="h",
        yanchor="bottom",
        y=1.02,
        xanchor="right",
        x=.4))
fig.update_layout({
    'legend_title_text': ''
},
    xaxis_title="",
    yaxis_title="Tested Count"

)
fig.update_xaxes(showline=True, linewidth=1, linecolor='#FBFBFB', mirror=False)
fig.update_yaxes(showgrid=True, gridwidth=1, gridcolor="#FBFBFB",showline=True, linewidth=2, linecolor='#FBFBFB', mirror=False)
fig.show()

enter image description here

谢谢大家


Tags: importtruedfgettitlefigupdateplotly
1条回答
网友
1楼 · 发布于 2024-09-26 22:13:14

为了使年份消失,您只需为xaxis_tickformat制定另一个规范,如xaxis_tickformat = '%b'即可获得:

enter image description here

或者您可以选择xaxis_tickformat = '%B'并获得:

enter image description here

在这两种情况下,年份都将根据您的请求删除

完整代码:

import plotly.graph_objects as go

import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

fig = go.Figure(go.Scatter(
    x = df['Date'],
    y = df['AAPL.High'],
))

fig.update_layout(
    title = 'Time Series with Custom Date-Time Format',
    #xaxis_tickformat = '%d %B (%a)<br>%Y'
    xaxis_tickformat = '%d %B <br>%Y'
    #xaxis_tickformat = '%B'

)

fig.show()

相关问题 更多 >

    热门问题