Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to modify a 2d Scatterplot to display color based on a third array in a CSV file?
To modify a 2D scatterplot to display color based on a third array in a CSV file, we use the c parameter in matplotlib's scatter() function. This allows us to map colors to data values, creating a visually informative plot.
Steps to Create a Color-Coded Scatterplot
- Read the CSV file with three columns of data
- Use the first two columns for X and Y coordinates
- Map the third column to colors using the
cparameter - Add a colorbar to show the color-to-value mapping
Example with Sample Data
Let's create a complete example that generates sample data and displays a color-coded scatterplot ?
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create sample CSV data
data = {
'x_values': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'y_values': [45, 98, 75, 54, 23, 35, 46, 57, 68],
'colors': [71, 65, 29, 63, 12, 27, 39, 44, 51]
}
df = pd.DataFrame(data)
# Set figure size
plt.rcParams["figure.figsize"] = [8.00, 6.00]
plt.rcParams["figure.autolayout"] = True
# Create the scatter plot with colors based on third column
fig = plt.figure()
ax = fig.add_subplot(111)
# Use 'c' parameter to map colors from the third column
scatter = ax.scatter(df.x_values, df.y_values, c=df.colors, marker="*", s=100, cmap='viridis')
# Add colorbar to show color mapping
plt.colorbar(scatter, label='Color Values')
# Add labels and title
ax.set_xlabel('X Values')
ax.set_ylabel('Y Values')
ax.set_title('2D Scatterplot with Color Mapping')
plt.show()
Key Parameters
| Parameter | Purpose | Example |
|---|---|---|
c |
Maps colors to data values | c=df.colors |
cmap |
Sets the colormap | cmap='viridis' |
s |
Controls marker size | s=100 |
Working with CSV Files
For actual CSV data, replace the sample data creation with file reading ?
# Read from actual CSV file
df = pd.read_csv("input.csv")
# Create scatter plot with color mapping
scatter = plt.scatter(df['data1'], df['data2'], c=df['data3'],
marker="*", s=100, cmap='plasma')
# Add colorbar
plt.colorbar(scatter, label='Data3 Values')
Popular Colormaps
-
viridis- Purple to yellow gradient -
plasma- Purple to pink gradient -
coolwarm- Blue to red gradient -
jet- Blue to red rainbow
Conclusion
Use the c parameter in scatter() to map colors from a third data column. Add a colorbar with plt.colorbar() to make the color mapping clear to viewers.
Advertisements
