H5W3
当前位置:H5W3 > 其他技术问题 > 正文

Matplotlib Snippets介绍

本文记录Matplotlib几种论文中常见类型图表的作图方式。

柱形图

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
dataset = ["Dataset 1", "Dataset 2"]
data = {"A": np.array([...]),
"B": np.array([...]),
"C": np.array([...]),
"D": np.array([...])}
best = "A"
# normalize(data)

x = np.arange(0,len(dataset)*3,3)
width = 0.15
fig, ax = plt.subplots(1,1,figsize=(6.5,3.5))
def normalize(data):
for key in data:
data[key] /= data[best]
def draw_bar(ax,title):
interval = np.arange(-len(data)+1,len(data),2)
for i, key in enumerate(data):
ax.bar(x + interval[i] * width, data[key], width*2, alpha=0.9, label=key)
ax.set_xticks(x)
ax.set_xticklabels(dataset)
# ax.set_yticks(np.arange(0, 8.5, 1.0))
    ax.set_xlabel("Dataset")
ax.set_ylabel("Normalized execution time")
# for i, v in enumerate(baseline/best):
    #     ax.text(i, v, str(v), color='black', fontweight='bold')
    ax.set_axisbelow(True)
ax.legend(loc=1,prop={"size":8})
ax.grid(axis='y')
if title != None:
ax.set_title(title)
draw_bar(ax)
# handles, labels = ax.get_legend_handles_labels()
# lgd = fig.legend(handles, labels, loc='upper center', mode="expand",ncol=3,columnspacing=0,bbox_to_anchor=(0.15, 0.62, 0.8, 0.5))
# fig.tight_layout()
plt.savefig(r"results.png",format="png",dpi=200,bbox_inches='tight')
plt.show()

折线图

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
fig, ax = plt.subplots(1,2,figsize=(8,3))
data = {"A": np.array([...]),
"B": np.array([...]),
"C": np.array([...])}
x = np.array((1,2,4,8,16,32,48))
colors = ["red", "#91cf60", "#4575b4"]
ticks = ["x", "o", "^"]
def draw_line(ax,title=None):
for i, key in enumerate(data):
ax.plot(x, data[key], color=colors[i])
ax.plot(x, data[key], ticks[i], color=colors[i], label=key)
ax.set_xscale('log',basex=2)
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.get_xaxis().get_major_formatter().labelOnlyBase = False
fmt = '%d' # Format you want the ticks, e.g. '40%'
    xticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)
ax.set_ylabel("Normalized execution time")
ax.set_xlabel("# of cores")
if title != None:
ax.set_title(title)
ax.legend()
draw_line(ax[0])
plt.tight_layout()
plt.savefig(r"fig/scale.pdf",format="pdf")
plt.show()

本文地址:H5W3 » Matplotlib Snippets介绍