I'm trying to change the legend names and I've found many answers but none of them works if you are not using traces. I learned to change the legend title but not the names. Here it is my code, hopefully somebody can help:
import pandas as pd
import plotly.express as px
import numpy as np
def camasRegion():
df = pd.read_csv('https://raw.githubusercontent.com/MinCiencia/Datos-COVID19/master/output/producto52/Camas_UCI.csv')
dates = df.columns #for some reason I can't use this as x axis
habilitadas = []
ocupadasCovid = []
ocupadasNoCovid = []
region = 'Ñuble'
for i in range(len(df)):
if df.values[i][0] == region:
if df.values[i][1] == 'Camas UCI habilitadas':
for x in range(len(df.columns)):
habilitadas.append(df.values[i][x])
if df.values[i][1] == 'Camas UCI ocupadas COVID-19':
for x in range(len(df.columns)):
ocupadasCovid.append(df.values[i][x])
if df.values[i][1] == 'Camas UCI ocupadas no COVID-19':
for x in range(len(df.columns)):
ocupadasNoCovid.append(df.values[i][x])
fig = px.line(df,
y = [habilitadas, ocupadasCovid, ocupadasNoCovid],
x = range(len(fechas)), #I'm doing this because x = dates doesn't work
title='Camas por región: (' region ')',)
fig.add_annotation(
x = 1, y = -0.1,
text = 'Fuente: Datos obtenidos desde el Ministerio de Ciencia.',
showarrow = False, xref='paper', yref='paper',
xanchor='right', yanchor='auto', xshift=0, yshift=-20
)
fig.update_layout(
legend_title_text='Estado de cama',
xaxis_title="Días",
yaxis_title="Cantidad de camas",
)
fig.show()
camasRegion()
CodePudding user response:
You can't use dates, because df.columns besides dates contains strings Region
and Serie
. I simplified your code, it also made it more readable. Try this and let me know, if it still not working for you.
import pandas as pd
import plotly.graph_objects as go
import numpy as np
def camasRegion():
df = pd.read_csv('https://raw.githubusercontent.com/MinCiencia/Datos-COVID19/master/output/producto52/Camas_UCI.csv')
region = "Ñuble"
target_region = df.query('Region == @region').drop('Region', axis=1).set_index('Serie').T
chart = []
for i in target_region:
if i != 'Camas base (2019)': #or you can easily drop it from your dataset
chart = [go.Scatter(x=target_region.index,y=target_region[i], name=i, mode='lines')]
fig = go.Figure(chart)
fig.update_layout(title={'text':f'Camas por región: ({region})', 'x':.45},
template='plotly_white', hovermode='x',
legend_title_text='Estado de cama',
xaxis_title="Días",
yaxis_title="Cantidad de camas")
fig.add_annotation(
x = 1, y = -0.1,
text = 'Fuente: Datos obtenidos desde el Ministerio de Ciencia.',
showarrow = False, xref='paper', yref='paper',
xanchor='right', yanchor='auto', xshift=0, yshift=-20
)
fig.show()
camasRegion()