0

Dispongo de un DataFrame con 10 columnas, cuyo contenido deseo representar en un gráfico de líneas, para lo cual hago:

import pandas as pd
import matplotlib as plt
(portfolio_df/portfolio_df.iloc[0]).plot(lw=1.5)
plt.show()

Las líneas se muestran correctamente, pero al generar el color automáticamente matplotlib, algún color se repite o es muy similar a otro.

Realizo otra prueba haciendo:

color = ['black', 'darkorange', 'green', 'blue', 'royalblue', 'darkviolet', 'fucsia', 'pinck', 'tomato', 'brown']

(portfolio_df/portfolio_df.iloc[0]).plot(color,  lw=1.5)
plt.show()

y me devuelve el error

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
/tmp/ipykernel_21873/1934979511.py in <module>
      1 color = ['black', 'darkorange', 'green', 'blue', 'royalblue', 'darkviolet', 'fucsia', 'pinck', 'tomato', 'brown']
      2 
----> 3 (portfolio_df/portfolio_df.iloc[0]).plot(color,  lw=1.5)
      4 plt.show()

~/anaconda3/envs/enri/lib/python3.9/site-packages/pandas/plotting/_core.py in __call__(self, *args, **kwargs)
    935                 if is_integer(x) and not data.columns.holds_integer():
    936                     x = data_cols[x]
--> 937                 elif not isinstance(data[x], ABCSeries):
    938                     raise ValueError("x must be a label or position")
    939                 data = data.set_index(x)

~/anaconda3/envs/enri/lib/python3.9/site-packages/pandas/core/frame.py in __getitem__(self, key)
   3509             if is_iterator(key):
   3510                 key = list(key)
-> 3511             indexer = self.columns._get_indexer_strict(key, "columns")[1]
   3512 
   3513         # take() does not accept boolean indexers

~/anaconda3/envs/enri/lib/python3.9/site-packages/pandas/core/indexes/base.py in _get_indexer_strict(self, key, axis_name)
   5794             keyarr, indexer, new_indexer = self._reindex_non_unique(keyarr)
   5795 
-> 5796         self._raise_if_missing(keyarr, indexer, axis_name)
   5797 
   5798         keyarr = self.take(indexer)

~/anaconda3/envs/enri/lib/python3.9/site-packages/pandas/core/indexes/base.py in _raise_if_missing(self, key, indexer, axis_name)
   5854                 if use_interval_msg:
   5855                     key = list(key)
-> 5856                 raise KeyError(f"None of [{key}] are in the [{axis_name}]")
   5857 
   5858             not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique())

KeyError: "None of [Index(['black', 'darkorange', 'green', 'blue', 'royalblue', 'darkviolet',\n       'fucsia', 'pinck', 'tomato', 'brown'],\n      dtype='object')] are in the [columns]"

¿Cómo puedo personalizar estos colores.?. Agradeceré ayuda.

1 respuesta 1

0

Estabas muy cerca. Debes usar el parámetro llamado color (y por cierto el color "fucsia" no existe en matplotlib, se escribe "fuchsia").

Un ejemplo, primero creo unos cuantos datos medio aleatorios (basados en una senoide con ruido):

import numpy as np
x = np.linspace(0, 3*np.pi, 50)
y = np.sin(x)
data = np.random.random(size=(len(x), 10))
for i in range(10):
  data[:,i] *= y
  data[:,i] += i*0.2

Ahora los convierto en un dataframe y lo ploteo con los colores por defecto:

import pandas as pd
df = pd.DataFrame(data)
ax = df.plot()
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

Sale así:

Colores por defecto

Ahora cambiando a los colores que tú querías:

colors = ['black', 'darkorange', 'green', 'blue', 'royalblue', 'darkviolet', 'fuchsia', 'pink', 'tomato', 'brown']
ax = df.plot(color = colors)
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

Y el resultado es:

Resultado deseado

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.