Plotly X-Achse-Etikett wird um einen Monat ausgeglichenPython

Python-Programme
Guest
 Plotly X-Achse-Etikett wird um einen Monat ausgeglichen

Post by Guest »

Code < /h1>

Code: Select all

import pandas as pd
import streamlit as st
import plotly.express
import plotly

data = {
'2024-01-31' :   1044,
'2024-02-29' :   2310,
'2024-03-31' :    518,
'2024-04-30' :  -1959,
'2024-05-31' :      0,
'2024-06-30' :  -1010,
'2024-07-31' :   1500,
'2024-08-31' : -15459,
'2024-09-30' : -14153,
'2024-10-31' : -12604,
'2024-11-30' :  -5918,
'2024-12-31' :  -3897
}

df = pd.DataFrame(data.items(), columns=['date', 'value'])

fig = plotly.express.bar(data_frame=df, x='date', y='value')

st.plotly_chart(fig)
< /code>
 Ausgabe < /h1>
In diesem Screenshot schwebt die Maus über die gesamte rechtliche Balken. sagt 31. Dezember 2024 
, was erwartet wird.
Beachten >
Workaround
Hier ist ein Ansatz für eine Problemumgehung: < /p>

Code: Select all

df['date'] = pd.to_datetime(df['date']).dt.to_period('M').dt.to_timestamp()
< /code>
Code: < /p>
import pandas as pd
import streamlit as st
import plotly.express
import plotly

data = {
'2024-01-31' :   1044,
'2024-02-29' :   2310,
'2024-03-31' :    518,
'2024-04-30' :  -1959,
'2024-05-31' :      0,
'2024-06-30' :  -1010,
'2024-07-31' :   1500,
'2024-08-31' : -15459,
'2024-09-30' : -14153,
'2024-10-31' : -12604,
'2024-11-30' :  -5918,
'2024-12-31' :  -3897
}

df = pd.DataFrame(data.items(), columns=['date', 'value'])

df['date'] = pd.to_datetime(df['date']).dt.to_period('M').dt.to_timestamp()

fig = plotly.express.bar(data_frame=df, x='date', y='value')

st.plotly_chart(fig)
Jetzt stimmen die X-Achsenbezeichnungen mit den Datenleisten Monaten überein:
< /p>
Notizen < /h1>
Die hier änderte Problemumgehung ändert im Grunde genommen jeden Datumswert vom Monat des Monats. bis zum ersten des Monat.>>> df
date value
0 2024-01-31 1044
1 2024-02-29 2310
2 2024-03-31 518
3 2024-04-30 -1959
4 2024-05-31 0
5 2024-06-30 -1010
6 2024-07-31 1500
7 2024-08-31 -15459
8 2024-09-30 -14153
9 2024-10-31 -12604
10 2024-11-30 -5918
11 2024-12-31 -3897
< /code>
Wir haben Folgendes: < /p>
>>> df
date value
0 2024-01-01 1044
1 2024-02-01 2310
2 2024-03-01 518
3 2024-04-01 -1959
4 2024-05-01 0
5 2024-06-01 -1010
6 2024-07-01 1500
7 2024-08-01 -15459
8 2024-09-01 -14153
9 2024-10-01 -12604
10 2024-11-01 -5918
11 2024-12-01 -3897
< /code>
Die Änderung erfolgt mit dieser Zeile: < /p>
df['date'] = pd.to_datetime(df['date']).dt.to_period('M').dt.to_timestamp()
< /code>
Frage < /h1>
Ist dies der empfohlene Ansatz zur Lösung dieses Problems? Oder gibt es eine idiomatischere Methode mit Plotly?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post