Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas: Using color in a scatter plot

I have a pandas dataframe:

--------------------------------------
|   field_0  |  field_1   | field_2  |
--------------------------------------
|     0      |   1.5      |  2.9     |
--------------------------------------
|     1      |   1.3      |  2.6     |
--------------------------------------
|       :                            |
--------------------------------------
|     1      |   2.1      |  3.2     |
--------------------------------------
|     0      |   1.1      |  2.1     |
--------------------------------------      

I can create a scatter plot for field_1 vs. field_2 like below:

%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
my_df.plot(x='field_1', y='field_2', kind = 'scatter')

However, I am wondering is it possible to include field_0 in the plot? So when field_0 = 0, the point is blue; when field_1 = 1, the point is red.

Thanks!

like image 676
Edamame Avatar asked Sep 18 '16 18:09

Edamame


People also ask

How do you add color to a scatter plot?

scatter( x , y , sz , c ) specifies the circle colors. You can specify one color for all the circles, or you can vary the color. For example, you can plot all red circles by specifying c as "red" .

Is it possible to create a Coloured scatterplot using Matplotlib?

Scatter Plot Color by Category using MatplotlibMatplotlib scatter has a parameter c which allows an array-like or a list of colors. The code below defines a colors dictionary to map your Continent colors to the plotting colors.

Is it possible to choose different color for each dots in the scatter plot?

Output: Now to change the colors of a scatterplot using plot(), simply select the column on basis of which different colors should be assigned to various points.

How do you plot a scatter plot on pandas?

To make a scatter plot in Pandas, we can apply the . plot() method to our DataFrame. This function allows you to pass in x and y parameters, as well as the kind of a plot we want to create.


1 Answers

you can do it this way:

col = df.field_0.map({0:'b', 1:'r'})
df.plot.scatter(x='field_1', y='field_2', c=col)

Result:

enter image description here

like image 70
MaxU - stop WAR against UA Avatar answered Oct 31 '22 09:10

MaxU - stop WAR against UA