不同类别使用不同颜色的散点图
Scatterplot using different colors for different categories
我想用 'x'、'y'、'type' 列(以及其他列和数千行)散点图 pandas DataFrame,其中 x, y是浮点数,'type' 是一个字符串,例如,"pear"、"apple" 或 "banana"。我想在 (x, y) 处根据类型用颜色画一个点。
我试过了:
df.plot.scatter(x='x', y='y', c='type', colormap=cmap)
定义如
cmap = colormap_from_dict({ 'pear': 'red', 'apple': 'blue', 'banana': 'yellow' })
但是我找不到这样的功能"colormap_from_dict"...你有解决办法吗?谢谢
根据记录,DataFrame 如下所示:
df = pd.DataFrame([[1, 2, 'banana'], [2, 1, 'apple'], [3, 3, 'pear']], columns=['x', 'y', 'type'])
您可以通过 lambda 函数应用颜色。
试试这个:
from matplotlib import pyplot as plt
import pandas as pd
df = pd.DataFrame([[1, 2, 'banana'], [2, 1, 'apple'], [3, 3, 'pear']], columns=['x', 'y', 'type'])
colors = { 'pear': 'red', 'apple': 'blue', 'banana': 'yellow' }
df.plot.scatter(x='x', y='y', c=df['type'].apply(lambda x: colors[x]))
plt.show()
我想用 'x'、'y'、'type' 列(以及其他列和数千行)散点图 pandas DataFrame,其中 x, y是浮点数,'type' 是一个字符串,例如,"pear"、"apple" 或 "banana"。我想在 (x, y) 处根据类型用颜色画一个点。
我试过了:
df.plot.scatter(x='x', y='y', c='type', colormap=cmap)
定义如
cmap = colormap_from_dict({ 'pear': 'red', 'apple': 'blue', 'banana': 'yellow' })
但是我找不到这样的功能"colormap_from_dict"...你有解决办法吗?谢谢
根据记录,DataFrame 如下所示:
df = pd.DataFrame([[1, 2, 'banana'], [2, 1, 'apple'], [3, 3, 'pear']], columns=['x', 'y', 'type'])
您可以通过 lambda 函数应用颜色。
试试这个:
from matplotlib import pyplot as plt
import pandas as pd
df = pd.DataFrame([[1, 2, 'banana'], [2, 1, 'apple'], [3, 3, 'pear']], columns=['x', 'y', 'type'])
colors = { 'pear': 'red', 'apple': 'blue', 'banana': 'yellow' }
df.plot.scatter(x='x', y='y', c=df['type'].apply(lambda x: colors[x]))
plt.show()