【问题标题】:Seaborn lineplot and barplot don't align in the X axis [duplicate]Seaborn 线图和条形图未在 X 轴上对齐 [重复]
【发布时间】:2021-01-31 18:07:14
【问题描述】:

好的,过去 5 个小时我一直被困在这里,但我似乎无法正确制作此组合图。

import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns


data = pd.read_csv('rating_conversion.csv')
df = pd.DataFrame(data)
overall_conversion_rate = df['overall_conversion_rate']
page_view_conversion = df['page_view_conversion']
Avg_Rating = df['avg_rating']
Total_Hired = df['total_hires']
df[:12]

fig, ax1 = plt.subplots(figsize=(10,6))
color = 'tab:green'
ax1.set_title('Total Hired and Avg Conversion % Per Rating Group', fontsize=16)
ax1.set_xlabel('Average_Rating', fontsize=16)
ax1.set_ylabel('Total_Hired', fontsize=16, color=color)
ax2 = sns.barplot(x=Avg_Rating, y=Total_Hired, data=df, palette='summer_r')
ax1.tick_params(axis='y')
ax2 = ax1.twinx()
color = 'tab:red'
ax2.set_ylabel('Avg Conversion %', fontsize=16, color=color)
ax2 = sns.lineplot(x=Avg_Rating, y=overall_conversion_rate, data=df, sort=False, color=color)
ax2.tick_params(axis='y', color=color)
plt.show()

我的期望是这样的,平均转化百分比和总雇佣人数共享相同的 X 轴。

enter image description here

请帮忙。 这是我一直用作示例的代码:

#Libraries
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

#Data
#create list of months
Month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June',
'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
#create list for made up average temperatures
Avg_Temp = [35, 45, 55, 65, 75, 85, 95, 100, 85, 65, 45, 35]
#create list for made up average precipitation %
Avg_Precipitation_Perc = [.90, .75, .55, .10, .35, .05, .05, .08, .20, .45, .65, .80]
#assign lists to a value
data = {'Month': Month, 'Avg_Temp': Avg_Temp, 'Avg_Precipitation _Perc': Avg_Precipitation_Perc}
#convert dictionary to a dataframe
df = pd.DataFrame(data)
#Print out all rows
df[:12]


#Create combo chart
fig, ax1 = plt.subplots(figsize=(10,6))
color = 'tab:green'
ax1.set_title('Average Precipitation Percentage by Month', fontsize=16)
ax1.set_xlabel('Month', fontsize=16)
ax1.set_ylabel('Avg Temp', fontsize=16, color=color)
ax2 = sns.barplot(x='Month', y='Avg_Temp', data = df, palette='summer')
ax1.tick_params(axis='y')
ax2 = ax1.twinx()
color = 'tab:red'
ax2.set_ylabel('Avg Precipitation %', fontsize=16, color=color)
ax2 = sns.lineplot(x='Month', y='Avg_Precipitation _Perc', data = df, sort=False, color=color)
ax2.tick_params(axis='y', color=color)
plt.show()

这是 rating_conversion.csv 的内容 https://paste.ubuntu.com/p/8w63wP2z9J/

【问题讨论】:

    标签: python pandas dataframe seaborn


    【解决方案1】:

    问题是 barplot 没有绘制在您的实际 x 值上。它将 x 变量视为分类变量,因此位置位于 x = 0、1、2 等处。另一方面,lineplot 使用 实际 x 值.您会在图中注意到线图位于第 5 条和第 6 条之间——对应于 x = 4 和 x = 5 之间的 x 位置。

    一种解决方法是使用pointplot 而不是lineplotpointplot 将 x 变量视为分类变量,类似于 barplot

    如果您重新计算 x 值,使它们从 0 开始并按 1 递增,您仍然可以使用 lineplot。一个简单的方法是使用 rank 方法。这比更改 barplot 以绘制实际 x 值更容易。

    顺便说一句,您并没有正确使用twinx。它有效,但您没有使用ax2。我将在示例中进行说明。

    问题

    import seaborn as sns
    tips = sns.load_dataset("tips")
    
    fig, ax = plt.subplots()
    ax_twin = ax.twinx()
    sns.barplot(x="day", y="total_bill", data=tips, ax=ax)
    sns.lineplot(x='day', y='total_bill', data=tips, err_style='bars', ax=ax_twin)
    

    使用pointplot:

    fig, ax = plt.subplots()
    ax_twin = ax.twinx()
    sns.barplot(x="day", y="total_bill", data=tips, ax=ax)
    sns.pointplot(x='day', y='total_bill', data=tips, ax=ax_twin)
    

    使用lineplotrank

    tips['rank'] = tips['size'].rank(method='dense') - 1
    
    fig, ax = plt.subplots()
    ax_twin = ax.twinx()
    sns.barplot(x='size', y='total_bill', data=tips, ax=ax)
    sns.lineplot(x='rank', y='total_bill', data=tips, err_style='bars', ax=ax_twin)
    

    【讨论】:

    • 非常感谢。使用 pointplot 工作并解决了我的问题。无论如何,线图有没有办法实际使用 x 轴类别而不是实际的 x 值?比如获取索引什么的?我对 python 很陌生,想知道是否有解决方法
    • 您可以将所有4.0s 替换为0,将4.2s 替换为1,等等。一个简单的方法是使用rank 方法。将method 设置为'dense',由于排名从 1 开始,因此您需要减去 1。
    猜你喜欢
    • 2017-03-18
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    相关资源
    最近更新 更多