Without the error bars, my plot looks great and the plotline colours match the symbol colours, but as soon as I add error bars, the colours of the plotlines seem to randomize (and not match the plot symbols):
plt.scatter(x1,y1, color='y', marker="s", alpha=0.6, s=50, label='House A')
plt.scatter(x2,y2, color='r', alpha=0.6, s=50, label='House B')
plt.scatter(x3,y3, color='c', marker='v', alpha=0.6, s=50, label='House C')
plt.scatter(x4,y4, color='g', marker='D', alpha=0.6, s=50, label='House D')
plt.plot(x1, y1, color='y')
plt.plot(x2, y2, color='r')
plt.plot(x3, y3, color='c')
plt.plot(x4, y4, color='g')
#error bars
plt.errorbar(x1,y1,yerr=y1error, ecolor='k', elinewidth=1, capsize=4, capthick=1,barsabove=False, alpha=1)
plt.errorbar(x2,y2,yerr=y2error, ecolor='k', elinewidth=1, capsize=4, capthick=1,barsabove=False, alpha=1)
plt.errorbar(x3, y3, yerr=y3error, ecolor='k', elinewidth=1, capsize=4, capthick=1,barsabove=False, alpha=1)
plt.errorbar(x4,y4,yerr=y4error, ecolor='k', elinewidth=1, capsize=4, capthick=1,barsabove=False, alpha=1)
Related
I want to draw a line&bar chart by Matplotlib, it seems the legend of chart will overlap on upper left part.
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
plt.figure(figsize=(7,5), dpi=100)
x = ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','>30']
y = [0.0964,0.1606,0.1651,0.1395,0.1105,0.0829,0.0603,0.0436,0.0328,0.0245,0.0183,0.0135,0.0105,0.0082,0.0061,0.0052,0.0041,0.0030,0.0024,0.0022,0.0013,0.0012,0.0010,0.0009,0.0009,0.0007,0.0006,0.0004,0.0005,0.0002,0.0023]
z = [11541,19234,19776,16704,13237,9931,7215,5218,3931,2936,2194,1619,1262,984,735,625,496,357,282,269,161,146,124,108,104,78,69,50,62,29,274]
plt.bar(x=x, height=z, label='Vehicles Num', color='Blue', alpha=0.7, width=0.5)
# plt.legend(loc="upper left")
plt.legend(loc="upper right")
plt.title("Frequency Distribution of Hood Ajar/Closed Events",size=18)
plt.xlabel("Frequency",size=15)
plt.ylabel("Number of Vehicles",size=15)
plt.yticks(size = 11)
plt.xticks(size = 11)
ax2 = plt.twinx()
ax2.set_ylabel("Percentage",size=15)
ax2.plot(y)
ax2.yaxis.set_major_formatter(ticker.PercentFormatter(xmax=1, decimals=1))
plt.plot(x, y, "r", marker='.', c='r', ms=8, linewidth='1', label="Percentage")
plt.legend(loc="upper right")
# for a, b in zip(x, y):
# plt.text(a, b, str(b*100)+'%', ha='center', va='bottom', fontsize=13)
#plt.savefig('cx483_2.jpg')
plt.show()
What can I do to make my legend more harmonious? Thanks a lot.
I use plt.subplots to plot a list of images.
Here is my code:
m, n, c = output.shape
fig, ax = plt.subplots(nrows=4, ncols=1)
fig.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
for i in range(4):
ax[i].imshow(output[:,:,i].reshape(m, n, 1), cmap='gray', vmin=0, vmax=1)
ax[i].axes.get_xaxis().set_visible(False)
ax[i].axes.get_yaxis().set_visible(False)
fig.set_facecolor('red')
plt.show()
And this is the result:
How can I remove the red space on the left and right of the figure?
I am sharing Y-axis in two subplots, with the following codes but both shared plots are missing legends in them.
projectDir = r'/media/DATA/banikr_D_drive/model/2021-04-28-01-18-15_5_fold_114sub'
logPath = os.path.join(projectDir, '2021-04-28-01-18-15_fold_1_Mixed_loss_dice.bin')
with open(logPath, 'rb') as pfile:
h = pickle.load(pfile)
print(h.keys())
fig, ax = plt.subplots(2, figsize=(20, 20), dpi=100)
ax[0].plot(h['dice_sub_train'], color='tab:cyan', linewidth=2.0, label="Train")
ax[0].plot(smooth_curve(h['dice_sub_train']), color='tab:purple')
ax[0].set_xlabel('Epoch/iterations', fontsize=20)
ax[0].set_ylabel('Dice Score', fontsize=20)
ax[0].legend(loc='lower right', fontsize=20)#, frameon=False)
ax1 = ax[0].twiny()
ax1.plot(h['dice_sub_valid'], color='tab:orange', linewidth=2.0, alpha=0.9, label="Validation" )
ax1.plot(smooth_curve(h['dice_sub_valid']), color='tab:red')
# , bbox_to_anchor = (0.816, 0.85)
ax[1].plot(h['loss_sub_train'], color='tab:cyan', linewidth=2.0, label="Train")
ax[1].plot(smooth_curve(h['loss_sub_train']), color='tab:purple')
ax2 = ax[1].twiny()
ax2.plot(h['loss_sub_valid'], color='tab:orange', linewidth=2.0, label="Validation", alpha=0.6)
ax2.plot(smooth_curve(h['loss_sub_valid']), color='tab:red')
ax[1].set_xlabel('Epoch/iterations', fontsize=20)
ax[1].set_ylabel('loss(a.u.)', fontsize=20)
ax[1].legend(loc='upper right', fontsize=20)
# ,bbox_to_anchor = (0.8, 0.9)
plt.suptitle('Subject wise dice score and loss', fontsize=30)
plt.setp(ax[0].get_xticklabels(), fontsize=20, fontweight="normal", horizontalalignment="center") #fontweight="bold"
plt.setp(ax[0].get_yticklabels(), fontsize=20, fontweight='normal', horizontalalignment="right")
plt.setp(ax[1].get_xticklabels(), fontsize=20, fontweight="normal", horizontalalignment="center")
plt.setp(ax[1].get_yticklabels(), fontsize=20, fontweight="normal", horizontalalignment="right")
plt.show()
Any idea how to solve the issue?
[1]: https://i.stack.imgur.com/kg7PY.png
ax1 has a twin y-axis with ax[0], but they are two separate axes. That's why ax[0].legend() does not know about the Validation line of ax1.
To have Train and Validation on the same legend, plot empty lines on the main axes ax[0] and ax[1] with the desired color and label. This will generate dummy Validation entries on the main legend:
...
ax[0].plot([], [], color='tab:orange', label="Validation")
ax[0].legend(loc='lower right', fontsize=20)
...
ax[1].plot([], [], color='tab:orange', label="Validation")
ax[1].legend(loc='upper right', fontsize=20)
...
I have created a 4x2 subplot and I want to save the individual plots as separate png files. I am able to do this with the following code, however the tightbbox format is too tight and it makes it tough to read the title and x,y labels. Is there a way to increase the padding (whitespace) around each individual plot when using this tightbbox layout?
nrow = combined.shape[0]
ncol = combined.shape[1]
shape_row = int((nrow + 1)/2 if (nrow % 2) != 0 else nrow/2)
fig, axes = plt.subplots(shape_row, 2, figsize=(20,45))
fig.subplots_adjust(hspace=0.5, wspace=0.4)
plt.rcParams['savefig.facecolor'] = 'white'
axes = axes.ravel()
for i in range(nrow):
axes[i].bar(range(2), combined.iloc[i,:2].values, color='blue', label=label_1)
axes[i].plot(range(2,ncol-1), combined.iloc[i,2:-1], 'o-', color='orange', markersize=10, label=label_2)
axes[i].plot([-1, 7], [combined.iloc[i,-1]]*2, linestyle='--', color='red', label=label_3)
axes[i].plot([ncol-1,ncol-1],[0, combined.iloc[i,-1]], '--', color='red')
axes[i].set_title(combined.index[i], fontsize=26, fontweight='bold', pad=15)
axes[i].set_xlabel('')
axes[i].set_ylabel("(in local currency '000s)", fontsize=18, labelpad=10)
axes[i].set_xticks(range(ncol))
axes[i].set_xticklabels(combined.columns, rotation=45)
axes[i].tick_params(labelsize=18, pad=10)
axes[i].set_xlim([-.7, nrow-.97])
axes[i].margins(x=0, y=0.2)
blue_bar= mpatches.Patch(color='blue', label='aaa')
orange_line=mlines.Line2D(range(2,ncol-1), combined.iloc[i,2:-1], color='orange', linestyle='-', marker = 'o', markersize=10, label='bbb')
red_line=mlines.Line2D([-1, 7], [combined.iloc[i,-1]]*2, color='red', linestyle='--', label='ccc')
lgd = axes[i].legend(handles=[blue_bar, orange_line, red_line],
loc='upper right', bbox_to_anchor=(1,1), fontsize=18, shadow=True, borderpad=1)
bbox = axes[i].get_tightbbox(fig.canvas.get_renderer())
fig.savefig("subplot{}.png".format(i),
bbox_inches=bbox.transformed(fig.dpi_scale_trans.inverted()))
I'd like to plot 3 function in one picture,but the third can't get,Is there anything with my code?
x = np.arange(-10., 10., 0.2)
simod1=sigmoid(x)
tanh1=tanh1(x)
relu1=relu(x)
pl.figure(num=1, figsize=(8, 6))
pl.title('Plot 1', size=14)
pl.xlabel('x-axis', size=14)
pl.ylabel('y-axis', size=14)
pl.plot(x, simod1, color='b', linestyle='--', marker='o', label='sigmoid')
pl.plot(x, tanh1, color='r', linestyle='-', label='tanh')
pl.plot(x, relu1, color='y', linestyle='*', label='relu')
pl.legend(loc='upper left')
pl.savefig('temp.png', format='png')
'*' is not a valid linestyle see the documentation http://matplotlib.org/api/lines_api.html#matplotlib.lines.Line2D.set_linestyle
I think you want to do this instead:
plt.plot(x, simod1, 'o--', color='b', label='sigmoid')
plt.plot(x, tanh1, '-', color='r', label='tanh')
plt.plot(x, relu1, '*', color='y', label='relu')