matplotlib 按列值为散点图着色

gmxoilav  于 2023-05-01  发布在  其他
关注(0)|答案(6)|浏览(139)

在R中使用ggplot2库时,我最喜欢的一个方面是能够轻松地指定美学。我可以快速地制作散点图,并应用与特定列相关联的颜色,我希望能够使用python/pandas/matplotlib来完成这一点。我想知道是否有任何方便的函数,人们使用pandas dataframes和Matplotlib将颜色Map到值?

##ggplot scatterplot example with R dataframe, `df`, colored by col3
ggplot(data = df, aes(x=col1, y=col2, color=col3)) + geom_point()

##ideal situation with pandas dataframe, 'df', where colors are chosen by col3
df.plot(x=col1,y=col2,color=col3)

编辑:谢谢你的回复,但我想包括一个样本数据框来澄清我的问题。两列包含数值数据,第三列是分类变量。我正在考虑的脚本将根据此值分配颜色。

np.random.seed(250)
df = pd.DataFrame({'Height': np.append(np.random.normal(6, 0.25, size=5), np.random.normal(5.4, 0.25, size=5)),
                   'Weight': np.append(np.random.normal(180, 20, size=5), np.random.normal(140, 20, size=5)),
                   'Gender': ["Male","Male","Male","Male","Male",
                              "Female","Female","Female","Female","Female"]})

     Height      Weight  Gender
0  5.824970  159.210508    Male
1  5.780403  180.294943    Male
2  6.318295  199.142201    Male
3  5.617211  157.813278    Male
4  6.340892  191.849944    Male
5  5.625131  139.588467  Female
6  4.950479  146.711220  Female
7  5.617245  121.571890  Female
8  5.556821  141.536028  Female
9  5.714171  134.396203  Female
afdcj2ne

afdcj2ne1#

导入和数据

import numpy 
import pandas
import matplotlib.pyplot as plt
import seaborn as sns
seaborn.set(style='ticks')

numpy.random.seed(0)
N = 37
_genders= ['Female', 'Male', 'Non-binary', 'No Response']
df = pandas.DataFrame({
    'Height (cm)': numpy.random.uniform(low=130, high=200, size=N),
    'Weight (kg)': numpy.random.uniform(low=30, high=100, size=N),
    'Gender': numpy.random.choice(_genders, size=N)
})

2021年8月更新

sns.relplot(data=df, x='Weight (kg)', y='Height (cm)', hue='Gender', hue_order=_genders, aspect=1.61)
plt.show()

2015年10月更新

Seaborn出色地处理了这个用例:

fg = sns.FacetGrid(data=df, hue='Gender', hue_order=_genders, aspect=1.61)
fg.map(plt.scatter, 'Weight (kg)', 'Height (cm)').add_legend()

其立即输出:

旧答案

在这种情况下,我会直接使用matplotlib。

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

def dfScatter(df, xcol='Height', ycol='Weight', catcol='Gender'):
    fig, ax = plt.subplots()
    categories = np.unique(df[catcol])
    colors = np.linspace(0, 1, len(categories))
    colordict = dict(zip(categories, colors))  

    df["Color"] = df[catcol].apply(lambda x: colordict[x])
    ax.scatter(df[xcol], df[ycol], c=df.Color)
    return fig

if 1:
    df = pd.DataFrame({'Height':np.random.normal(size=10),
                       'Weight':np.random.normal(size=10),
                       'Gender': ["Male","Male","Unknown","Male","Male",
                                  "Female","Did not respond","Unknown","Female","Female"]})    
    fig = dfScatter(df)
    fig.savefig('fig1.png')

这给了我:

据我所知,颜色列可以是任何matplotlib兼容的颜色(RBGA元组、HTML名称、十六进制值等)。
除了数值,我在使用色彩Map表时遇到了麻烦。

lnvxswe2

lnvxswe22#

实际上你可以使用ggplot for python

from ggplot import *
import numpy as np
import pandas as pd

df = pd.DataFrame({'Height':np.random.randn(10),
                   'Weight':np.random.randn(10),
                   'Gender': ["Male","Male","Male","Male","Male",
                              "Female","Female","Female","Female","Female"]})

ggplot(aes(x='Height', y='Weight', color='Gender'), data=df)  + geom_point()

ncgqoxb0

ncgqoxb03#

https://seaborn.pydata.org/generated/seaborn.scatterplot.html

import numpy 
import pandas
import seaborn as sns

numpy.random.seed(0)
N = 37
_genders= ['Female', 'Male', 'Non-binary', 'No Response']
df = pandas.DataFrame({
    'Height (cm)': numpy.random.uniform(low=130, high=200, size=N),
    'Weight (kg)': numpy.random.uniform(low=30, high=100, size=N),
    'Gender': numpy.random.choice(_genders, size=N)
})

sns.scatterplot(data=df, x='Height (cm)', y='Weight (kg)', hue='Gender')

xvw2m8pv

xvw2m8pv4#

您可以使用plot方法的*color参数来定义每列所需的颜色。例如:

from pandas import DataFrame
data = DataFrame({'a':range(5),'b':range(1,6),'c':range(2,7)})
colors = ['yellowgreen','cyan','magenta']
data.plot(color=colors)

您可以使用颜色名称或颜色十六进制代码,如“#000000”表示黑色。你可以在matplotlib'swww.example中找到所有定义的颜色名称 www.example.com 。py文件在matplotlib的github仓库中。
https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/colors.py

f3temu5u

f3temu5u5#

导入和测试数据

  • 'Date'已经是DataReaderdatetime64[ns] dtype
  • conda install -c anaconda pandas-datareaderpip install pandas-datareader,具体取决于环境。
import pandas as pd
import matplotlib.pyplot as plt
import pandas_datareader as web  # for data; not part of pandas

tickers = 'amzn'
df = web.DataReader(ticker, data_source='yahoo', start='2018-01-01', end='2021-01-01').reset_index()
df['ticker'] = ticker

        Date        High          Low         Open        Close   Volume    Adj Close ticker
0 2018-01-02  1190.00000  1170.510010  1172.000000  1189.010010  2694500  1189.010010   amzn
1 2018-01-03  1205.48999  1188.300049  1188.300049  1204.199951  3108800  1204.199951   amzn

c作为数字

pandas.DataFrame.plot

  • df.Date.dt.month创建pandas.Series个月数
ax = df.plot(kind='scatter', x='Date', y='High', c=df.Date.dt.month, cmap='Set3', figsize=(11, 4), title='c parameter as a month number')
plt.show()

matplotlib.pyplot.scatter

fig, ax = plt.subplots(figsize=(11, 4))
ax.scatter(data=df, x='Date', y='High', c=df.Date.dt.month, cmap='Set3')
ax.set(title='c parameter as a month number', xlabel='Date', ylabel='High')
plt.show()

c作为datetime dtype

pandas.DataFrame.plot

ax = df.plot(kind='scatter', x='Date', y='High', c='Date', cmap='winter', figsize=(11, 4), title='c parameter as a datetime dtype')
plt.show()

matplotlib.pyplot.scatter

fig, ax = plt.subplots(figsize=(11, 4))
ax.scatter(data=df, x='Date', y='High', c='Date', cmap='winter')
ax.set(title='c parameter as a datetime dtype', xlabel='Date', ylabel='High')
plt.show()

wpx232ag

wpx232ag6#

虽然不是matplotlib,但可以使用plotly express实现:

import numpy as np
import pandas as pd
import plotly.express as px

df = pd.DataFrame({
    'Height':np.random.normal(size=10),
    'Weight':np.random.normal(size=10),
    'Size': 1,  # How large each point should be?
    'Gender': ["Male","Male","Male","Male","Male","Female","Female","Female","Female","Female"]})

# Create your plot
px.scatter(df, x='Weight', y='Height', size='Size', color='Gender')

如果在notebook中创建,您将获得如下交互式输出:

相关问题