18

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.

1 Answer 1

35

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

Sign up to request clarification or add additional context in comments.

3 Comments

How do I specify custom colors to be used as a colormap? For example if I want to use only two custom colors as a colormap.
Now the command is cmap = cm.Spectral in the new version of matplolib
Further colormaps can be found there: matplotlib.org/stable/users/explain/colors/colormaps.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.