如何用分类和数值(数据)轴绘制折线图?

2024-10-03 15:28:00 发布

您现在位置:Python中文网/ 问答频道 /正文

Seaborn使您能够使用点创建分类图

import seaborn as sns

tips = sns.load_dataste('tips')
sns.catplot(x='tip', y='sex', data=tips, jitter=False)

enter image description here

有没有一种方法可以把同一性别的点和线连接起来

我的目标是创建一个类似下图的图(在R's ggplot2中完成)。阅读seaborn documentation我发现没有什么能像这样的情节。lineplot只接受数值。现在有没有一个明显的方法让我错过这个明确的情节

enter image description here


Tags: 方法importdataas分类loadseabornsns
1条回答
网友
1楼 · 发布于 2024-10-03 15:28:00

按类别分组并分别绘制每条线

import numpy as np
import matplotlib.pyplot as plt

def cat_horizontal_plot(data, category, numeric, ax=None):
    ax = ax or plt.gca()
    for cat, num in data.groupby(category):
        ax.plot(np.sort(num[numeric].values), [cat]*len(num),
                marker="o", mec="k", mfc="none", linestyle="-", color="k")
    ax.set_xlabel(numeric)
    ax.set_ylabel(category)
    ax.margins(y=0.4)
    ax.figure.tight_layout()

把它当作

import seaborn as sns
tips = sns.load_dataset('tips')

cat_horizontal_plot(tips, "sex", "tip")
plt.show()

enter image description here

相关问题 更多 >