color bar and marker are not matching color by using geoplot

84 views Asked by At

I am plotting the location of earthquake at various places using lattitude and longitude. I use geojson data to plot a map and then use columns name 'Longitude' and 'Latitude' to plot the marker on map. But the color of marker and color bar is not same the circle with 8.2 marker should be more dark red as per color bar but it is yellowish in map. How to solve this?

geojson_path = '/content/drive/MyDrive/ColabNotebooks/Practice/nepal.geojson'
gdf = gpd.read_file(geojson_path)


# Read CSV file using Pandas
mydata = pd.read_csv('/content/drive/MyDrive/ColabNotebooks/Practice/earthquakes.tsv', sep='\t')
df = mydata[mydata['Mag'].notnull()]

# Create a GeoDataFrame from the DataFrame with latitude and longitude
geometry = gpd.points_from_xy(df['Longitude'], df['Latitude'])
gdf_points = gpd.GeoDataFrame(df, geometry=geometry)
# Set up the subplots to take up the whole width
fig, ax = plt.subplots(figsize=(15, 8)) 

# Define a colormap and normalize values based on the 'Mag' column
cmap = plt.get_cmap('YlOrRd')  # You can choose any other colormap
norm = Normalize(vmin=df['Mag'].min(), vmax=df['Mag'].max())


# Plot the GeoDataFrame with points, adjusting circle size based on the 'size' column
gdf.plot(ax=ax)

scatter = gdf_points.plot(
    ax=ax, 
    cmap=cmap,
    markersize=(df['Mag']) * 200,
    c=df['Mag'],  # Assign 'Mag' values as the color
    norm=norm,
    alpha=1
)

# Add colorbar for reference
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])  # You need to set an array to the ScalarMappable
cbar = plt.colorbar(sm, ax=ax, label='Magnitude')

# Annotate each point with its 'size' value
for x, y, label in zip(df['Longitude'], df['Latitude'], df['Mag']):
    plt.text(x, y, str(label), color='white', ha='center', va='center')

plt.title('Map with Points from CSV')
plt.show()

[enter image description here]

1

There are 1 answers

4
alec_djinn On

You have set alpha=0.5. Alpha is a measure of "transparency"; in your case, the marker color is 50% mixed with the background blue. Set alpha=1 if you want the markers to have a solid color matching the color scale.

Also, you forgot to normalize the color. If you share your dataframe I can make an example ad hoc. In the meantime, look at this toy example:

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize


my_data = list(range(10,50))

#choose a color map
cmap = cm.gist_rainbow
vmin = min(my_data)
vmax = max(my_data)

#normalize coordinates
norm = Normalize(vmin, vmax)

for x,y in enumerate(my_data):
    plt.scatter(
        x, y,
        color=cmap(norm(y)) #color from normalized value
    )
plt.title('Example Colormap')
plt.show()

enter image description here

Try this modified version of your code:

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize
import matplotlib.cm as cm


download = "/Users/alec/Downloads/dataFrame"

geojson_path = f'{download}/nepal.geojson'
tsv_path = f'{download}/earthquakes.tsv'

gdf = gpd.read_file(geojson_path)
mydata = pd.read_csv(tsv_path, sep='\t')
df = mydata[mydata['Mag'].notnull()]

# Create a GeoDataFrame from the DataFrame with latitude and longitude
geometry = gpd.points_from_xy(df['Longitude'], df['Latitude'])
gdf_points = gpd.GeoDataFrame(df, geometry=geometry)
# Set up the subplots to take up the whole width
fig, ax = plt.subplots(figsize=(15, 8)) 

# Define a colormap and normalize values based on the 'Mag' column
#cmap = cm.gist_rainbow
vmin = df['Mag'].min()
vmax = df['Mag'].max()
norm = Normalize(vmin, vmax)
cmap = plt.get_cmap('YlOrRd')  # You can choose any other colormap
norm = Normalize(vmin=df['Mag'].min(), vmax=df['Mag'].max())

# Plot the GeoDataFrame with points, adjusting circle size based on the 'size' column
gdf.plot(ax=ax)

scatter = gdf_points.plot(
    ax=ax, 
    markersize=(df['Mag']) * 200,
    color=cmap(norm(df['Mag'])) #colormap based on normalized values
)

# Annotate each point with its 'size' value
for x, y, label in zip(df['Longitude'], df['Latitude'], df['Mag']):
    plt.text(x, y, str(label), color='black', ha='center', va='center')

# Add colorbar for reference
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])  # You need to set an array to the ScalarMappable
cbar = plt.colorbar(sm, ax=ax, label='Magnitude')

plt.title('Map with Points from CSV')
plt.show()

enter image description here