Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use colormaps to color plots of Pandas DataFrames

I have a pd.DataFrame like this one:

ColumnName
1
1
2
3
1
2
3
1
2
2

I can plot it with df['ColumnName'].plot(style='o')

How I can define different colors for the different values in the column (for example red for value 1, green for 2, orange for 3). I know it has to do with colormap, but how I can use it?

An solution is to construct a new DataFrame with the columns of every value. But these values are sorted and I want have exactly this sequence just colored in the different colors.

like image 227
Guforu Avatar asked Sep 09 '14 09:09

Guforu


People also ask

How do I visualize pandas DataFrame?

In order to visualize data from a Pandas DataFrame , you must extract each Series and often concatenate them together into the right format. It would be nicer to have a plotting library that can intelligently use the DataFrame labels in a plot.

How do you add a legend to a pandas plot?

Basics Data Science with Numpy, Pandas and Matplotlib Make a dictionary d with keys Column1 and Column2. Make a data frame using DataFrame (d). Plot the data frame with a list of styles. Using legend(), place a legend on the figure.

How do you color a column in pandas?

@sqllearner you can apply the same color to several columns just by adding them to the subset, like df. style. set_properties(**{'background-color': 'red'}, subset=['A', 'C']).


1 Answers

To plot the first column from your dataframe, try something like this:

from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.randint(20, size=20))
cmap = cm.get_cmap('Spectral') # Colour map (there are many others)

fig, ax = plt.subplots(1)
# Now here's the plot. range(len(df)) just makes the x values 1, 2, 3...
# df[0] is then the y values. c sets the colours (same as y values in this
# case). s is the marker size.
ax.scatter(range(len(df)), df[0], c=df[0], s=120, cmap=cmap, edgecolor='None')
plt.show()

Which results in:Plot output

like image 166
LondonRob Avatar answered Oct 17 '22 06:10

LondonRob