如何在重叠打印中对齐直方图箱边

2024-04-26 00:23:29 发布

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

我已经设法得到了两个直方图叠加,但如果你仔细看,这些条开始倾斜,没有完全重叠

我已经调整了线宽和宽度,但并没有改善它

我的目标是让所有的酒吧都排成一排,没有黑色边缘的歪斜

有没有办法解决这个问题

这是我的密码:

import matplotlib.pyplot as plt
import numpy

True_Distance = sort_by_Distance_below_4kpc_and_retrabmag_no_99s["true distance"].tolist()
Retr_Distance = sort_by_Distance_below_4kpc_and_retrabmag_no_99s["retrieved distance from observed parallax"].tolist()


plt.figure(figsize=(8,6))
plt.hist(True_Distance, normed=True, bins = 40, alpha=0.75, color = "mediumorchid", label="True Distance", edgecolor='black', linewidth=0.1, width=200)
plt.hist(Retr_Distance, normed=True, bins = 20, alpha=0.5, color = "lightskyblue", label="Retrieved Distance", edgecolor='black', linewidth=0.1, width=200)

# Add title and axis names
plt.title('Number distribution of stars with distance')
plt.xlabel('Distance (parsecs)')
plt.ylabel('Number of stars')
plt.legend()

输出结果如下:

Output Histogram


Tags: andnoimporttruebypltsorthist
2条回答
  • 有两种方法可以处理箱子边缘对齐
    1. 如果'distance'类别(例如'methods')和值以整洁的格式分别提供,则^{}API将在使用hue参数时正确对齐各种类别的箱子边缘。
      • 要使用此选项,必须堆叠列,以便测量方法在一列中,距离在另一列中,这可以通过以下代码行完成
      • df = sort_by_Distance_below_4kpc_and_retrabmag_no_99s[['true distance', 'retrieved distance from observed parallax']].stack().reset_index(level=1).rename(columns={'level_1': 'method', 0: 'distance'})
    2. 如注释中的JohanC所述,如果单独绘制数据(如OP中所示),则必须指定箱子边缘
  • ^{}^{}的高级API
  • 本例中的数据集是从seaborn样本数据集导入的,并在NASA Exoplanet Explorations中解释。距离地球是光年

样本数据及;进口

  • plants数据集与星形距离数据集非常吻合。这里'method'有几个值
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["patch.force_edgecolor"] = True

# import some test data
df = sns.load_dataset('planets')

# display(df.head())
            method  number  orbital_period   mass  distance  year
0  Radial Velocity       1         269.300   7.10     77.40  2006
1  Radial Velocity       1         874.774   2.21     56.95  2008
2  Radial Velocity       1         763.000   2.60     19.84  2011
3  Radial Velocity       1         326.030  19.40    110.62  2007
4  Radial Velocity       1         516.220  10.50    119.47  2009

将所有'methods'绘制在一起

  • 如您所见,无论如何指定bins,边始终对齐
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(10, 10))
data = df[df.distance < 801]
sns.histplot(data=data, x='distance', hue='method', ax=ax1, bins=np.arange(0, 801, 80))
sns.histplot(data=data, x='distance', hue='method', ax=ax2, bins=20)
sns.histplot(data=data, x='distance', hue='method', ax=ax3)

enter image description here

分别选择'method'并打印

  • 当为两组数据定义相同的边时,仅为ax2对齐bin边
  • 使用sns.histplot进行绘图,而不使用hue,“大部分”等同于使用^{}进行绘图
    • 有一些不同的默认设置。例如binssns.hist使用autoplt.hist默认值为10,正如seaborn的创建者mwaskom所指出的那样
# create a dataframe for two values from the method column
radial = data[data.method == 'Radial Velocity']
transit = data[data.method == 'Transit']

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(10, 10))

# number of bins and edges determined by the API
sns.histplot(data=transit, x='distance', color="lightskyblue", ax=ax1)
sns.histplot(data=radial, x='distance', color="mediumorchid", ax=ax1)

# bin edges defined the same for both plots
sns.histplot(data=transit, x='distance', bins=np.arange(0, 801, 40), color="lightskyblue", ax=ax2)
sns.histplot(data=radial, x='distance', bins=np.arange(0, 801, 40), color="mediumorchid", ax=ax2)

# a number of bins is specifice, edges determined by API based on the data
sns.histplot(data=transit, x='distance', bins=20, color="lightskyblue", ax=ax3)
sns.histplot(data=radial, x='distance', bins=20, color="mediumorchid", ax=ax3)

enter image description here

您是否为直方图和x轴定义了仓位大小。您应该为两个直方图定义相同的x轴,并在每个直方图中为它们提供相同数量的箱。然后,当您绘制它们时,它们应该沿x轴相同,但不同的箱子的高度不同

相关问题 更多 >

    热门问题