基于第三变量带颜色条的双变量散点图绘制报错及方案咨询
Fixing Scatter Plot with Color Mapping (Jet Colormap) & Resolving the
TypeError Let's break down what's going wrong with your code first, then walk through two solid solutions to get the exact plot you want.
What Caused the TypeError?
Your original code has two main issues:
- When you called
plt.scatter(df['A'], df['B'], cmap="jet"), you didn't pass thecparameter to link the scatter points to yourz(df['C']) values. Without this, the scatter plot doesn't have a data array associated with its colormap, hence the "must first set_array for mappable" error when trying to add a colorbar. - You're mixing
matplotlib.pyplot.scatterandseaborn.lmplotin the same script—these create separate figure objects, so they won't combine into one plot like you're expecting.
Solution 1: Pure Matplotlib Implementation (Simple & Direct)
This approach uses only matplotlib to create your scatter plot with the Jet colormap, linked directly to your z values:
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Generate your data x = np.random.randint(0, 20, 30) y = np.random.randint(-5, 5, 30) z = np.random.randint(-2, 10, 30) df = pd.DataFrame(data={'A': x, 'B': y, 'C': z}) # Create the scatter plot, linking color to df['C'] with Jet colormap scatter = plt.scatter(df['A'], df['B'], c=df['C'], cmap='jet') # Add colorbar with a label for clarity plt.colorbar(scatter, label='Z Value') # Add axis labels plt.xlabel('X (A)') plt.ylabel('Y (B)') plt.show()
Key Fixes Here:
- Added
c=df['C']toplt.scatterto map point colors to yourzvariable. - Removed the unnecessary
cm.ScalarMappableline—matplotlib handles the colormap mapping automatically when you passcandcmap. - No conflicting seaborn calls, so everything stays in one figure.
Solution 2: Seaborn with Jet Colormap
If you prefer using seaborn, you don't have to abandon the Jet colormap. You can explicitly set palette='jet' in seaborn.scatterplot (a better fit than lmplot for pure scatter plots):
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # Generate data (same as before) x = np.random.randint(0, 20, 30) y = np.random.randint(-5, 5, 30) z = np.random.randint(-2, 10, 30) df = pd.DataFrame(data={'A': x, 'B': y, 'C': z}) # Create seaborn scatter plot with Jet colormap sns.scatterplot(data=df, x='A', y='B', hue='C', palette='jet', s=50) # Customize the colorbar label plt.colorbar(label='Z Value') # Add axis labels plt.xlabel('X (A)') plt.ylabel('Y (B)') plt.show()
Why This Works:
sns.scatterplotsupports thepaletteparameter, so you can directly specify'jet'to use that colormap.- Using
hue='C'links the point colors to yourzvalues, just like thecparameter in matplotlib. - We use
scatterplotinstead oflmplotbecauselmplotis designed for regression plots (even withfit_reg=False, it adds extra overhead and creates a FacetGrid, which is unnecessary here).
Both solutions will produce a scatter plot where points are colored based on your z values using the Jet colormap, matching the style of your reference example.
内容的提问来源于stack exchange,提问作者gis20
相关产品推荐
相关产品推荐

