python - 在 matplotlib + numpy 中布置几个图

标签 python numpy

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

  1. 如何将标题放在两个图和
  2. 之上
  3. 如何在机器人图中插入一些文本
  4. 如何引用上下图

对于我的第一个任务,我使用了 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

最佳答案

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

  • 使用 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

关于python - 在 matplotlib + numpy 中布置几个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20615094/

相关文章:

python - Jython 的 Numpy 模拟

python - numpy 如何排序数组切片索引?

python - 使用不同的 python 安装 virtualenv 时断言错误

python - 如何为 argparse 参数提供类型提示?

python - 在Python中,如何对一个迭代对象进行多次迭代?

python - 如何在python中替换特定单词后的下一个单词

Python/ML : Which methods to use for Multiclass Classification for Product Categorization?

python - 填充靠近图像区域的元素

python - 将 MATLAB 转换为 Python : too many indices return error

numpy - numpy中的Theano开关