在matplotlib + numpy中布置几个图

时间:2013-12-16 15:55:27

标签: python numpy

我是python的新手,想要使用下面的直方图和热图来绘制数据集。但是,我有点困惑

  1. 如何将标题置于两个图和
  2. 之上
  3. 如何在博彩地块中插入一些文字
  4. 如何参考上下图
  5. 对于我的第一项任务,我使用了title指令,该指令在两个图之间插入了一个标题,而不是将其放在两个图上方

    对于我的第二项任务,我使用了figtext指令。但是,我在剧情的任何地方都看不到文字。我玩了一些x,y和fontsize参数没有任何成功。

    这是我的代码:

    def drawHeatmap(xDim, yDim, plot, threshold, verbose):
    global heatmapList
    stableCells = 0
    
    print("\n[I] - Plotting Heatmaps ...")
    for currentHeatmap in heatmapList:
        if -1 in heatmapList[currentHeatmap]:
            continue
        print("[I] - Plotting heatmap for PUF instance", currentHeatmap,"(",len(heatmapList[currentHeatmap])," values)")
        # Convert data to ndarray
        #floatMap = list(map(float, currentHeatmap[1]))
        myArray = np.array(heatmapList[currentHeatmap]).reshape(xDim,yDim)
    
        # Setup two plots per page
        fig, ax = plt.subplots(2)
    
        # Histogram        
        weights = np.ones_like(heatmapList[currentHeatmap]) / len(heatmapList[currentHeatmap])
        hist, bins = np.histogram(heatmapList[currentHeatmap], bins=50, weights=weights)
        width = 0.7 * (bins[1] - bins[0])
        center = (bins[:-1] + bins[1:]) / 2
        ax[0].bar(center, hist, align='center', width=width)
        stableCells = calcPercentageStable(threshold, verbose)
        plt.figtext(100,100,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!", fontsize=40)
    
    
        heatmap = ax[1].pcolor(myArray, cmap=plt.cm.Blues, alpha=0.8, vmin=0, vmax=1)
        cbar = fig.colorbar(heatmap, shrink=0.8, aspect=10, fraction=.1,pad=.01)
        #cbar.ax.tick_params(labelsize=40) 
        for y in range(myArray.shape[0]):
            for x in range(myArray.shape[1]):
                plt.text(x + 0.5, y + 0.5, '%.2f' % myArray[y, x],
                 horizontalalignment='center',
                 verticalalignment='center',
                 fontsize=(xDim/yDim)*5
                 )
    
        #fig = plt.figure()
        fig = matplotlib.pyplot.gcf()
        fig.set_size_inches(60.5,55.5)
        plt.savefig(dataDirectory+"/"+currentHeatmap+".pdf", dpi=800, papertype="a3", format="pdf")
        #plt.title("Heatmap for PUF instance "+str(currentHeatmap[0][0])+" ("+str(numberOfMeasurements)+" measurements; "+str(sizeOfMeasurements)+" bytes)")
        if plot:
            plt.show()
        print("\t[I] - Done ...") 
    

    这是我当前的输出:output

1 个答案:

答案 0 :(得分:2)

也许这个例子会让事情变得更容易理解。需要注意的是:

  • 使用fig.suptitle将标题添加到图的顶部。
  • 使用ax[i].text(x, y, str)向Axes对象添加文本
  • 您的案例中的每个Axes对象ax[i]都包含有关单个图的所有信息。使用它们而不是调用plt,这只适用于每个图形的一个子图,或者一次修改所有子图。例如,不要调用plt.figtext,而是调用ax[0].text将文字添加到顶部图中。

请尝试按照下面的示例代码进行操作,或者至少仔细阅读以便更好地了解如何使用ax列表。


import numpy as np
import matplotlib.pyplot as plt

histogram_data = np.random.rand(1000)
heatmap_data = np.random.rand(10, 100)

# Set up figure and axes
fig = plt.figure()
fig.suptitle("These are my two plots")
top_ax = fig.add_subplot(211) #2 rows, 1 col, 1st plot
bot_ax = fig.add_subplot(212) #2 rows, 1 col, 2nd plot
# This is the same as doing 'fig, (top_ax, bot_ax) = plt.subplots(2)'

# Histogram
weights = np.ones_like(histogram_data) / histogram_data.shape[0]
hist, bins = np.histogram(histogram_data, bins=50, weights=weights)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2

# Use top_ax to modify anything with the histogram plot
top_ax.bar(center, hist, align='center', width=width)
# ax.text(x, y, str). Make sure x,y are within your plot bounds ((0, 1), (0, .5))
top_ax.text(0.5, 0.5, "Here is text on the top plot", color='r')

# Heatmap
heatmap_params = {'cmap':plt.cm.Blues, 'alpha':0.8, 'vmin':0, 'vmax':1}

# Use bot_ax to modify anything with the heatmap plot
heatmap = bot_ax.pcolor(heatmap_data, **heatmap_params)
cbar = fig.colorbar(heatmap, shrink=0.8, aspect=10, fraction=.1,pad=.01)

# See how it looks
plt.show()

enter image description here