Home > OS >  Coloring based on specific conditions for Scatter Plot in Python
Coloring based on specific conditions for Scatter Plot in Python

Time:04-13

My goal right now is to create sub scatter plots for regions in Europe.

fig, axes = plt.subplots(2,2,figsize=(10,8))
fig.tight_layout(h_pad=5.0,w_pad=3.0)

color = ['red', 'blue', 'orange']
# red = if temperature above 10
# blue = if temperature below 6
# orange = if temperature between 6 and 10 (inclusive)

# first figure for 'No EU and No Coastline'
lat1 = visualize1['latitude']
axes[0][0].scatter(city_count1List,lat1.values)
axes[0][0].set_title('No EU and No Coastline')
axes[0][0].set_xlabel('City')
axes[0][0].set_ylabel('Latitude')

# second figure for 'No EU and Yes Coastline'
lat2 = visualize2['latitude']
axes[0][1].scatter(city_count2List,lat2.values)
axes[0][1].set_title('No EU and Yes Coastline')
axes[0][1].set_xlabel('City')
axes[0][1].set_ylabel('Latitude')

# third figure for 'Yes EU and No Coastline'
lat3 = visualize3['latitude']
axes[1][0].scatter(city_count3List,lat3.values)
axes[1][0].set_title('Yes EU and No Coastline')
axes[1][0].set_xlabel('City')
axes[1][0].set_ylabel('Latitude')

# fourth figure for 'Yes EU and Yes Coastline'
lat4 = visualize4['latitude']
axes[1][1].scatter(city_count4List,lat4.values)
axes[1][1].set_title('Yes EU and Yes Coastline')
axes[1][1].set_xlabel('City')
axes[1][1].set_ylabel('Latitude')

plt.show()

The result I get is what I want in terms of formatting. enter image description here

But what I want to do is make the plots different colors depending on the temperature of the region. Here's an example of one of the charts that are being graphed. enter image description here

If the temperature is above 10, then the plot will be red.

If the temperature is between 6 and 10 (inclusive), the plot will be orange.

If the temperature is below 6, then the plot will be blue.

Is there some way I can do this with the code above?

CodePudding user response:

Created a categorical color column based on the condition & applied color

import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

city = ["abc","def","ghi","jkl","mno","pqr","stu","vwx", "yza", "bcd"]
eu = ["no","no","no","no","no","no","no","no","no","no"]
coast = ["no","no","no","no","no","no","no","no","no","no"]
lat = [42.50,52.61,52.10,42,47.76,44.82,44.82,6.68,6.43,8.40]
temp = [7.50,5.61,4.10,8,9.76,10.82,3.82,4.68,1.43,5.40]

df1 = pd.DataFrame({'city':city, 'eu':eu, 'coast':coast, 'latitude':lat, 'temprature':temp})


df1.loc[df1['temprature'] > 10, 'color'] = 'R'
df1.loc[((df1['temprature'] > 6) & (df1['temprature'] <= 10)), 'color'] = 'O'
df1.loc[df1['temprature'] < 6, 'color'] = 'B'

fig, ax = plt.subplots(figsize=(6, 6))
colors = {'R':'tab:red', 'O':'tab:orange', 'B':'tab:blue'}
ax.scatter(df1['temprature'], df1['latitude'], c=df1['color'].map(colors))

handles = [Line2D([0], [0], marker='o', color='w', markerfacecolor=v, label=k, markersize=8) for k, v in colors.items()]
ax.legend(title='color', handles=handles, bbox_to_anchor=(1.05, 1), loc='upper left')

plt.show()

CodePudding user response:

I don't have time to manually copy the data you posted in the pictures, so I'm going to generate random data.

There are many ways to apply conditional colors. This is my approach:

import numpy as np
import matplotlib.pyplot as plt

# generate random data
x = np.random.uniform(0, 1, 10)
y = np.random.uniform(0, 1, 10)
temp = np.array([1, 4, 5, 6, 7, 8, 9, 10, 11, 12])

# the idea is to build a list of colors.
# Please, read help(plt.scatter) to understand
# how colors should be presented. Also, read this
# documentation page:
# https://matplotlib.org/3.5.0/tutorials/colors/colors.html

# insert your conditions here (I'm going to use Tab10 colors)
def case(t):
    if t > 10:
        return "tab:red"
    elif (t > 6) and (t <= 10):
        return "tab:orange"
    return "tab:blue"
colors = [col_dict[case(t)] for t in temp]

plt.figure()
plt.scatter(x, y, c=colors)
plt.xlabel("City")
plt.ylabel("Latitude")

enter image description here

  • Related