Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/277.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Matplotlib中绘制多个直方图-颜色或并排条形图_Python_Matplotlib_Histogram_Matplotlib Basemap - Fatal编程技术网

Python 在Matplotlib中绘制多个直方图-颜色或并排条形图

Python 在Matplotlib中绘制多个直方图-颜色或并排条形图,python,matplotlib,histogram,matplotlib-basemap,Python,Matplotlib,Histogram,Matplotlib Basemap,问题:在Matplotlib中绘制多个直方图时,我无法将一个图与另一个图区分开来 问题如图所示:** **小问题:左侧标签“计数”部分超出图像范围。为什么? 说明 我想绘制3个不同集合的直方图。每个集合都是一个包含0和1的数组。我想要每个的柱状图,这样我就可以检测数据集上的不平衡 我把它们分开画了出来,但我想把它们画在一起 如果有一个不同的图形并排显示,或者,我甚至在谷歌上搜索过将其绘制为3D,那也没关系,但我不知道“阅读”或“查看”图形并理解它有多容易 现在,我想在同一个图形的每一侧绘制[tr

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

问题如图所示:** **小问题:左侧标签“计数”部分超出图像范围。为什么?

说明

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

我把它们分开画了出来,但我想把它们画在一起

如果有一个不同的图形并排显示,或者,我甚至在谷歌上搜索过将其绘制为3D,那也没关系,但我不知道“阅读”或“查看”图形并理解它有多容易

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

PS:我的谷歌搜索没有返回任何我可以理解的代码。 此外,我想如果有人会检查,如果我做任何疯狂我的代码

谢谢大家

代码:

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()

    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()
现在开始工作了,但左侧的标签有点超出范围,我想更好地将横杆居中。。。我该怎么做?


结果:

我试着想出了这个。您可以更改代码中的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))

我试图运行的确切代码(将存储箱数量更改为2后)——


A我也得到了同样的结果…

如果数据集长度相等,您可能可以轻松地使用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()
这导致了这幅图:

如果您还导入seaborn,它看起来会更好一些:


我需要保存图像。。您提供的代码可能吗?@ScientistGirl是的,像往常一样使用savefig。看起来它现在确实起作用了!但是,你能帮我解决这个小问题吗?我想在XLabel上更好地将这些条居中!而且左边的标签是不允许的!您已经删除了
bin
param,默认设置为10。只需像这样添加一个bins参数-
n,bins,patches=plt.hist(Y,bins=2,normed=False,alpha=0.75,range=histrange,label=labels)
您是否尝试过将存储箱设置为2?关于未显示的标签,我想这是一个特定于机器的问题。你可以试着调整子批次…看看这是否有效!嗯,如果你不介意的话,再问一个问题。。我能把图片放大一点吗?与图像宽度*2和高度*2一样,默认值是rcParams['figure.figsize']=(1,1)?
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()