I'm plotting, but find that I need to increase the area underneath chart such that I can plot the labels vertically but in a font size that is not so tiny. At the moment, I have:
plt.figure(count_fig) fig, ax = plt.subplots()
rects1 = ax.bar(ind, ratio_lst, width, color='r', linewidth=1, alpha=0.8, log=1)
ax.set_ylabel('')
ax.set_title('')
ax.set_xticks(ind_width)
ax.set_xticklabels(labels_lst, rotation='vertical', fontsize=6)
At the moment it works, but the labels often run-off the edge of the plot.
subplots_adjust will do it. You can play with the bottom keyword to get a good placement of the bottom of the plot.
fig.subplots_adjust(bottom=0.2)
Related
I am trying to make a clear visualizatin of my data.
This is my code:
width = 0.5
plt.figure(figsize=(10,8))
counts1, bins, bars = plt.hist(data=df1_small, x='fz', bins=np.arange(-5, 5.5, width), color='dodgerblue', alpha=0.3) #rwidth can change the space between bars
#plt.plot(bins[:-1] + width/2, counts1, color='#FF6103', linewidth=2)
counts2, bins, bars = plt.hist(data=df2_big, x='fz', bins=np.arange(-5, 5.5, width), color='red', alpha=0.1)
#plt.plot(bins[:-1] + width/2, counts2, color='#76EEC6', linewidth=2)
labels = ["small", "big"]
plt.legend(labels)
plt.grid(False)
#plt.savefig("./figure/acce.eps", dpi=300)
plt.savefig("./figure/acce.png", dpi=300)
plt.show()
Whenever I plot, I found that color is overlapped if plot is overlapped.
Is there any idea to avoid this overlap?
This is my plot right now:
I want to avoid color overlapping and make it clear with just two colors.
Thank you
If you want to avoid any overlap between the two histograms, you could plot both in separate subplots. In this case, I think it makes more sense to title the axes than to add labels, but you could do either. See below:
# Create two subplots, aligned horizontally
fig, axes = plt.subplots(1, 2, figsize=(10, 8))
width = 0.5
# Plot each histogram in its own axis
counts1, bins, bars = axes[0].hist(data=df1_small, x='fz', bins=np.arange(-5, 5.5, width), color='dodgerblue', alpha=0.3) #rwidth can change the space between bars
counts2, bins, bars = axes[1].hist(data=df2_big, x='fz', bins=np.arange(-5, 5.5, width), color='red', alpha=0.1)
# Add title
axes[0].set_title("small")
axes[1].set_title("small")
# Add labels
axes[0].legend("small")
axes[1].legend("big")
# Need to disable the grid for both axes
axes[0].grid(False)
axes[1].grid(False)
plt.savefig("./figure/acce.png", dpi=300)
plt.show()
I'm trying to reproduce the following image using matplotlib
I figured I have two options to deal with the top and bottom grid lines: format the top/bottom spine to match the formatting of the grid lines, or turn off all spines and just display grid lines. I've gone with the latter, as it seems more straightforward:
ax.spines[:].set_visible(False)
ax.set_axisbelow(True)
ax.grid(True, axis='y', color='#9E9E9E')
This works for the top grid line, but the bottom of the plot displays the tick marks but not the bottom grid line:
Is it possible to make a grid line also appear at the bottom without changing the y-limits?
ax.grid() has a parameter clip_on= that can be set to False to avoid clipping by the axes borders.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
bars = ax.bar(['left', 'right'], [13160, 11569], color=['dimgrey', 'goldenrod'])
ax.bar_label(bars)
ax.spines[:].set_visible(False)
ax.set_axisbelow(True)
ax.grid(True, axis='y', color='#9E9E9E', clip_on=False)
ax.set_ylim(ymin=10000)
ax.tick_params(length=0) # hide tick marks
ax.axhline(10968, color='dodgerblue', lw=1.5)
ax.set_yticks([10000, 10968, 12000, 13000, 14000])
ax.get_yticklabels()[1].set_color('dodgerblue')
plt.show()
I am using the following code to contour plot some data using contourf in matplotlib. I have set the transparency of the colourbar to 0.6, but there are annoying lines between each colour interval that I cant get rid of. There doesnt seem to be a way to set linestyle in contourf, any ideas?
#instantiating and titiling the figure
fig, ax1 = plt.subplots(figsize=(7,5))
fig.suptitle('Testing Simple Neural Networks', y=0.96, fontsize=16, fontweight='bold');
#defining colour tables
cm = plt.cm.coolwarm
#plotting the contour plot
levels = np.linspace(0, 1, 25)
cont1 = ax1.contourf(p1_mesh, p2_mesh, y_mesh, levels=levels, cmap=cm, alpha=0.6, linewidths=10)
#plotting the entire dataset - training and test data.
scat1 = ax1.scatter(X['p1'],
X['p2'],
c=y,
cmap=cm,
edgecolors='k');
#setting axis and legend
ax1.set(ylabel='p2',
xlabel='p1',
xlim=(0,255),
ylim=(0,255));
ax1.legend(*scat1.legend_elements(), title='Target');
ax1.set_axisbelow(True)
ax1.grid(color='xkcd:light grey')
cbar = fig.colorbar(cont1)
You can add the option antialiased=True to ax1.contourf, it should fix it.
In a plot with inset axes, I want to mark the inset using mpl_toolkits.axes_grid1.inset_locator.mark_inset. However, I'm running into trouble controlling the zorder and clipping of the resulting lines marking the inset. The inset axes are set to zorder=4, and I'm using:
fig = plt.figure()
fig.set_tight_layout(False)
ax = fig.gca()
x = np.arange(4500.0, 10000.0)
ax.plot(x, 700-x/20.0+20*np.sin(x/8.0), label="Skylines")
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition, mark_inset, inset_axes
inset_ax = fig.add_axes([0,0,1,1], zorder=4, frameon=True)
inset_ax.set_axes_locator(InsetPosition(ax, [0.1, 0.1, 0.4, 0.5]))
inset_ax.plot(x, 700-x/20.0+20*np.sin(x/8.0))
inset_ax.set_xlim(8800, 8850)
inset_ax.set_ylim(230, 285)
# inset_ax.set_ylim(100, 600)
mark_inset(ax, inset_ax, loc1=2, loc2=3, linewidth=0.7, fc="None", ec='k', alpha=0.4, clip_on=True, zorder=3)
ax.axhline(y=300, c='r', label="Test")
leg = ax.legend(ncol=1, loc='upper center', frameon=True, framealpha=1.0)
leg.set_zorder(5)
plt.show()
which, for two different cases in y limits, results in
The unwanted behaviour here is that the inset lines appear across the inset axes (while the line marked Test is placed nicely behind the inset axes), and outside of the main axes (and through the legend), respectively. I would have expected the zorder and clip_on arguments to fix this, but they don't seem to have an effect.
Case 1
zorder is evaluated on a per axis base. Since the connector lines are added to the inset axes, they will always be on top of the axes background. An option is to remove them from the inset axes and add them to the original one.
Case 2
The connectors are explicitely not clipped in the matplotlib source code, because as part of the inset axes you would not ever want them to be clipped by the inset axes.
However, if they are part of the original axes, you can set clipping to on again.
In total
ret = mark_inset(ax, inset_ax, loc1=2, loc2=3, linewidth=0.7, fc="None", ec='k', alpha=0.4)
for bc in ret[1:]:
bc.remove()
ax.add_patch(bc)
bc.set_zorder(4)
bc.set_clip_on(True)
I want to change the rotation of the xticks, but I am ending with x AND yticks rotated. How can I rotate just the xticks?
Here is my code:
# Plot mit Sidestepped 0/1
sns.set(style="darkgrid")
fig, ax = plt.subplots(1,2, figsize=(14,5))
for i in range(len(ax)):
ax[i].tick_params(labelsize=15)
ax[i].set_xlabel('label', fontsize=17, position=(.5,20))
ax[i].set_ylabel('label', fontsize=17)
sns.countplot(x="page_name", hue="successful", data=mainDf, ax=ax[0]);
sns.countplot(x="industry", hue="successful", data=mainDf, ax=ax[1]);
fig.suptitle('Categorical Features Count', position=(.5,1.1), fontsize=20)
ax[0].set_title('Type by Industry', fontsize=18)
ax[0].set_xlabel('Industry')
ax[0].tick_params(rotation=50)
ax[1].set_title('Success by Industry', fontsize=18)
ax[1].set_xlabel('Industry')
fig.tight_layout()
fig.show()
And here is what I get (x BUT unfortunately also yticks rotated! Look at just the left plot at ax[0]! I want to rotate just the xticks of the left plot!):
You can use the axis argument for tick_params to specify the rotation for a specific axis:
ax[0].tick_params(axis="x", rotation=50)