Just my first post, it should a very easy one. I have to do an exercise in which i have a dataframe with several variables and i have to produce a scatter graph where i plot in the y axis the "Price", in the x axis the "Weight" and where i apply a specific color pattern to the dots based on the "Priority" (which goes from 1 to 10).
The defined colors to be applied are:
`colors=["navy","lawngreen","red","green","purple","steelblue","orange","darkred","yellow","chocolate"]
`
So "Priority=1" should be colors="navy", "Priority=2" should be colors="lawngreen",etc
Therefore i tried to do the following:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df=pd.read_csv("example.csv")
plt.scatter(df.Price,df.Weight,c=df.Priority,s=90)
plt.colorbar()
plt.xlabel('Price')
plt.ylabel('Weight');
``
But the coloring that i get obviously does not match the colors predefined (they is just a ramdon color assigned to each of the values of "Priority" variable. How do i link the defined colors with the Priority variable values? I tried to build a dictionary to use it in the c argument of the plt.scatter line but i couldnt get any proper result so maybe i'm formulating it wrongly.
Thanks in advance
First thing first, there is a miss match between your graph definition and what you actually do:
a scatter graph where i plot in the y axis the "Price", in the x axis the "Weight"
but you plot "Price" along the x axis and "Weight" along the y axis :
# [...]
plt.scatter(df.Price, df.Weight, c=df.Priority, s=90)
plt.xlabel('Price')
plt.ylabel('Weight')
Getting back to your main question, you're on the good track. Simply define a custom colormap from the list of colors with ListedColormap
(see doc here) and it should be good.
Here is an example with fake data for price, weight and priority (only 3 priority values here)
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
# Fake data
price = np.random.randint(0, 100, size=(100))
weight = price + np.random.randint(-20, 20, size=(100))
priority = np.random.randint(0, 3, size=(100))
# Create the custom colormap
colors = ["navy", "lawngreen", "red"]
cmap = ListedColormap(colors)
# Scatter with priority as color and the correct colormap
plt.scatter(weight, price, c=priority, cmap=cmap, s=90)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments