如何使用 matplotlib 和 numpy 将此直方图转换为点 plot/dot 图表?

How do I convert this histogram into a dot plot/dot chart using matplotlib and numpy?

我正在尝试根据学生的睡眠时间创建点 plot/dot 图表,但我能得到的最接近的是一个与我的数据相匹配的直方图。由于我完全缺乏经验或与我的数据不兼容,下面将提供的我尝试的方法对我不起作用。任何帮助将不胜感激。

我已经试过一个类似的答案是这样的:

此方法将睡眠时间中的浮点值四舍五入,这导致绘图不正确,或者我可能只是使用错误。我将不胜感激使用我的确切示例的解决方案,因为我对编程仍然很陌生并且可能不会了解太多其他内容。

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline

hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5, 6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
bin_list = []

for number in hours_of_sleep:
    if number not in bin_list:
        bin_list.append(number)
        bin_list.sort()
        item_1 = bin_list[0]
        item_2 = bin_list[-1]


proper_bin = np.arange(item_1, item_2+1, 0.5)


plt.hist([hours_of_sleep], bins=proper_bin, rwidth= 0.8)
plt.title('Hours of Sleep for Students')

plt.show()

我想以点图示例结束,该示例由在我已经提供的 link 中提出问题的用户提供。

我觉得这回答了你的问题:

我使用的方法大致相同。

import matplotlib.pyplot as plt
import numpy as np

hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5, 6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
bins = np.arange(0, max(hours_of_sleep) + 1, 0.5)

hist, edges = np.histogram(hours_of_sleep, bins=bins)

y = np.arange(1, hist.max() + 1)
x = np.arange(0, max(hours_of_sleep) + 0.5, 0.5)
X,Y = np.meshgrid(x,y)

plt.scatter(X, Y, c = Y<=hist, cmap="Blues")
plt.xticks(np.arange(max(hours_of_sleep) + 2))
plt.yticks([])
plt.title('Hours of Sleep for Students')
plt.show()

替代方法

import matplotlib.pyplot as plt
import numpy as np

hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5, 6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
bins = np.arange(0, max(hours_of_sleep) + 1, 0.5)

hist, edges = np.histogram(hours_of_sleep, bins=bins)

y = np.arange(1, hist.max() + 1)
x = np.arange(0, max(hours_of_sleep) + 0.5, 0.5)
X,Y = np.meshgrid(x,y)

Y = Y.astype(np.float)
Y[Y>hist] = None
plt.scatter(X, Y)
plt.xticks(np.arange(max(hours_of_sleep) + 2))
plt.yticks([])
plt.title('Hours of Sleep for Students')
plt.show()

希望这对您有所帮助。 :)
阅读一些 Matplotlib Documentations 也会对您有所帮助。

我建议如下,因为它很简单:

from collections import Counter
import matplotlib.pyplot as plt

hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5, 6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
z = Counter(hours_of_sleep)

ar = 0.2
fig, ax = plt.subplots(figsize=(plt.figaspect(ar)))
for key, value in z.items():
    X = [key] * value
    Y = [item + 1 for item in range(value)]
    plt.scatter(X, Y, color='b', s=100)

plt.xlabel('response')
plt.ylabel('occurrence')
plt.title('Dotplot-histogram')
plt.tight_layout()
plt.show()

结果如下:

您可以通过遍历 np.unique(hours_of_sleep, return_counts=True) 返回的唯一 valuescounts 的数组来绘制每一列点来创建点图。以下是如何创建类似于 :

中所示示例的绘图
import numpy as np                 # v 1.19.2
import matplotlib.pyplot as plt    # v 3.3.2

hours_of_sleep = [9, 6 ,8, 6, 8, 8, 6, 6.5, 6, 7, 9, 4, 3, 4, 5,
                  6, 11, 6, 3, 6, 6, 10, 7, 8, 4.5, 9, 7, 7]
values, counts = np.unique(hours_of_sleep, return_counts=True)

fig, ax = plt.subplots(figsize=(6, 3))
for value, count in zip(values, counts):
    ax.plot([value]*count, list(range(count)), c='tab:blue', marker='o',
            ms=10, linestyle='')
for spine in ['top', 'right', 'left']:
    ax.spines[spine].set_visible(False)
ax.yaxis.set_visible(False)
ax.set_ylim(-1, max(counts))
ax.set_xticks(range(int(min(values)), int(max(values)+1)))
ax.tick_params(axis='x', length=0, pad=8, labelsize=12)
ax.set_title('Hours of Sleep for Students', pad=30, fontsize=14)

plt.show()


您可以找到更多 ,其中一些格式化参数是根据数据自动设置的。