【问题标题】:Plotting Multiple Histograms in Matplotlib - Colors or side-by-side bars在 Matplotlib 中绘制多个直方图 - 颜色或并排条
【发布时间】:2016-11-01 13:58:51
【问题描述】:

问题:在 Matplotlib 中绘制多个直方图时,我无法区分一个图与另一个图

图片问题:** **小问题:左侧标签“计数”部分不在图像中。为什么?

说明

我想绘制 3 个不同集合的直方图。每个集合都是一个包含 0 和 1 的数组。我想要每个的直方图,这样我就可以检测数据集上的不平衡。

我将它们分开绘制,但我想将它们放在一起。

可以有一个不同的图形并排并排,或者,我什至用谷歌搜索将它绘制为 3D,但我不知道“阅读”或“查看”图形有多容易明白了。

现在,我想在同一图形的每一侧绘制 [train]、[validation] 和 [test] 条,如下所示:

PS:我的谷歌搜索没有返回任何我可以理解的代码。 另外,我想是否有人会检查我是否对我的代码做了任何 insanity

非常感谢大家!

代码:

def generate_histogram_from_array_of_labels(Y=[], labels=[], xLabel="Class/Label", yLabel="Count", title="Histogram of Trainset"):
    plt.figure()
    plt.clf()

    colors = ["b", "r", "m", "w", "k", "g", "c", "y"]

    information = []
    for index in xrange(0, len(Y)):
        y = Y[index]

        if index > len(colors):
            color = colors[0]
        else:
            color = colors[index]

        if labels is None:
            label = "?"
        else:
            if index < len(labels):
                label = labels[index]
            else:
                label = "?"

        unique, counts = np.unique(y, return_counts=True)
        unique_count = np.empty(shape=(unique.shape[0], 2), dtype=np.uint32)

        for x in xrange(0, unique.shape[0]):
            unique_count[x, 0] = unique[x]
            unique_count[x, 1] = counts[x]

        information.append(unique_count)

        # the histogram of the data
        n, bins, patches = plt.hist(y, unique.shape[0], normed=False, facecolor=color, alpha=0.75, range=[np.min(unique), np.max(unique) + 1], label=label)

    xticks_pos = [0.5 * patch.get_width() + patch.get_xy()[0] for patch in patches]

    plt.xticks(xticks_pos, unique)

    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    plt.title(title)
    plt.grid(True)
    plt.legend()
    # plt.show()

    string_of_graphic_image = cStringIO.StringIO()

    plt.savefig(string_of_graphic_image, format='png')
    string_of_graphic_image.seek(0)

    return base64.b64encode(string_of_graphic_image.read()), information

编辑

按照哈希码的答案,这个新代码:

def generate_histogram_from_array_of_labels(Y=[], labels=[], xLabel="Class/Label", yLabel="Count", title="Histogram of Trainset"):
    plt.figure()
    plt.clf()

    colors = ["b", "r", "m", "w", "k", "g", "c", "y"]
    to_use_colors = []
    information = []


    for index in xrange(0, len(Y)):
        y = Y[index]

        if index > len(colors):
            to_use_colors.append(colors[0])
        else:
            to_use_colors.append(colors[index])

        unique, counts = np.unique(y, return_counts=True)
        unique_count = np.empty(shape=(unique.shape[0], 2), dtype=np.uint32)

        for x in xrange(0, unique.shape[0]):
            unique_count[x, 0] = unique[x]
            unique_count[x, 1] = counts[x]

        information.append(unique_count)

    unique, counts = np.unique(Y[0], return_counts=True)
    histrange = [np.min(unique), np.max(unique) + 1]
    # the histogram of the data
    n, bins, patches = plt.hist(Y, 1000, normed=False, alpha=0.75, range=histrange, label=labels)


    #xticks_pos = [0.5 * patch.get_width() + patch.get_xy()[0] for patch in patches]

    #plt.xticks(xticks_pos, unique)

    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    plt.title(title)
    plt.grid(True)
    plt.legend()

正在制作这个:

-- 新编辑:

def generate_histogram_from_array_of_labels(Y=[], labels=[], xLabel="Class/Label", yLabel="Count", title="Histogram of Trainset"):
    plt.figure()
    plt.clf()

    information = []

    for index in xrange(0, len(Y)):
        y = Y[index]

        unique, counts = np.unique(y, return_counts=True)
        unique_count = np.empty(shape=(unique.shape[0], 2), dtype=np.uint32)

        for x in xrange(0, unique.shape[0]):
            unique_count[x, 0] = unique[x]
            unique_count[x, 1] = counts[x]

        information.append(unique_count)

    n, bins, patches = plt.hist(Y, normed=False, alpha=0.75, label=labels)

    plt.xticks((0.25, 0.75), (0, 1))

    plt.xlabel(xLabel)
    plt.ylabel(yLabel)
    plt.title(title)
    plt.grid(True)
    plt.legend()

现在正在工作,但是左侧的标签有点超出范围,我想更好地居中条形...我该怎么做?

结果:

【问题讨论】:

  • 您已删除bins 参数,默认设置为10。只需添加一个像这样的bins 参数-n, bins, patches = plt.hist(Y, bins = 2, normed=False, alpha=0.75, range=histrange, label=labels)
  • 您是否尝试将 bin 设置为 2?
  • 关于该标签未显示,我猜它是特定于机器的问题。您可以尝试调整子图...查看matplotlib.org/examples/pylab_examples/subplots_adjust.html
  • 成功了!嗯,如果你不介意,再问一个问题.. 我可以把图形放大吗?像图片宽度*2和高度*2
  • 默认为 rcParams['figure.figsize'] = (1, 1) ?

标签: python matplotlib histogram matplotlib-basemap


【解决方案1】:

我尝试并想出了这个。您可以更改代码中的 xticks 位置。只需将一个元组传递给plt.hist,再简单不过了!?因此,假设您有两个 0 和 1 列表,那么您要做的是 -

a = np.random.randint(2, size=1000)
b = np.random.randint(2, size=1000)
plt.hist((a, b), 2, label = ("data1", "data2"))
plt.legend()
plt.xticks((0.25, 0.75), (0, 1))

我尝试运行的确切代码(将 bin 数量更改为 2 后)-

a = np.random.randint(2, size=1000)
b = np.random.randint(2, size=1000)
y = [a, b]
labels = ["data1", "data2"]
generate_histogram_from_array_of_labels(Y = y, labels = labels)

我得到了同样的结果...

【讨论】:

  • 现在看来它确实有效了!但是,你能帮我解决这个小问题吗?我想将条形图更好地集中在 xlabels 上!左边的标签也越界了!
【解决方案2】:

如果您的数据集长度相等,您可以使用 pandas 轻松完成此操作。所以假设你有

import numpy

N = 1000
train, validation, test = [numpy.random.randint(2, size=N) for _ in range(3)]
Y = [train, validation, test]

你可以这样做

import pandas

df = pandas.DataFrame(list(zip(*Y)), columns=['Train', 'Validation', 'Test'])
df.apply(pandas.value_counts).plot.bar()

这导致了这个情节:

如果你也import seaborn,看起来会更好一点:

【讨论】:

  • 我需要保存图像.. 你提供的这段代码可以吗?
  • @ScientistGirl 是的,照常使用 savefig。
猜你喜欢
  • 1970-01-01
  • 2019-08-19
  • 2016-08-13
  • 1970-01-01
  • 2014-05-24
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多