1

Aprendiendo Plotly. Disponemos del siguiente DataFrame

import pandas_datareader.data as pdr
start = "2016-1-4"
end = "2020-10-19"
iberdrola = pdr.DataReader("IBE.MC", "yahoo", start, end)
iberdrola = iberdrola[["Close"]]
iberdrola[:3]

Utilizando matplotlib, repesento la gráfica de la evolución en el tiempo de la variable y una recta horizontal representando el valor medio de la cotización.

# Import Matplotlib's `pyplot` module as `plt`
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot') 
%matplotlib inline

""" Figure 32 """
# Creating a figure, setting its size and plotting close prices on it
fig = plt.figure(figsize=(10, 5))
plt.plot(iberdrola, color='purple')

# Customizing the axes
plt.xticks(rotation=45, color='teal', size=12)
plt.yticks(rotation=45, color='teal', size=12)

# Setting axes labels
plt.xlabel('Fechas', {'color': 'orange', 'fontsize':15})
plt.ylabel('Precios', {'color': 'orange', 'fontsize':15})

# Importing NumPy library
import numpy as np

# Calculating the mean value of close prices
mean_price = np.mean(iberdrola["Close"])

# Plotting the horizontal line along with the close prices
plt.axhline(mean_price, color='r', linestyle='dashed')

# Importing DateTime from DateTime library
from datetime import datetime

# Plotting text on date 2014-1-7 and price 120
plt.text(datetime(2016,5,7), 8, 'Precio medio', size=15, color='r') # coordenadas x e y, texto,size y color

plt.show()

Deseo hacer lo mismo utilizando plotly. Consigo representar la gráfica de la siguiente manera.

# Usando plotly.express
import plotly.express as px

# Precio medio de las cotizaciones
mean_price = np.mean(iberdrola["Close"])

df = iberdrola.reset_index()
fig = px.line(df, x='Date', y="Close")
fig.show()

En este punto me he quedado bloqueado y no he sido capaz de representar en la misma gráfica la línea horizontal y el texto. Agradeceré ayuda para superar este paso.

1 respuesta 1

1

Pintar una línea se hace llamando a fig.add_shape() y especificando los parámetros apropiados. El texto se añade con fig.add_annotation().

La parte más "difícil" aquí es las coordenadas x0 y x1 de inicio y fin de línea, o la coordenada x del texto, ya que estas coordenadas son fechas. No obstante se resuelve de forma simple si las sacamos del propio dataframe:

df = iberdrola.reset_index()
x0 = df["Date"].iloc[0]            # La primera
x1 = df["Date"].iloc[-1]           # La última
xm = df["Date"].iloc[len(df)//2]   # La del medio

Ahora pintamos la gráfica y la línea encima, y el texto 10 píxeles por encima de la línea:

mean_price = np.mean(iberdrola["Close"])

fig = px.line(df, x="Date", y="Close")

fig.add_shape(type="line",
    x0=x0, y0=mean_price, x1=x1, y1=mean_price,
    line=dict(color="Red",width=3)
 )

fig.add_annotation(x=xm, y=mean_price,
            text='Precio medio',
            showarrow=False,
            yshift=10)

Resultado:

introducir la descripción de la imagen aquí

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.