for some reason my minor ticks in my plot are not showing anymore. Yesterday, I still had them in and I just don't know what I changed such that they disappeared...
Here is my code:
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager
fig, axs = plt.subplots(nrows=1, ncols=1, sharex=True, sharey=True)
font = font_manager.FontProperties(family='sans-serif', style='normal', size=16)
for (i, alpha) in enumerate(alpha_values_small):
filt = data[
(data["Topology"] == "UNIFORM") &
(data["HashingPowerDistribution"] == "UNIFORM") &
(data["CentralityMeasure"] == "RANDOM") &
(data["Alpha"] == alpha)]
axs.plot(
1/filt["Gamma"],
filt["OrphanBlockRate"],
label=r"$\alpha = {}$".format(np.round(alpha, 2)),
color=color_list[i],
marker=marker_list[i],
linestyle="",
markersize=12,
linewidth=1.5,
markeredgewidth=2,
)
axs.set_xscale("log")
axs.set_xlabel(r"$\lambda_{nd}$", fontfamily='sans-serif', fontsize=22)
axs.set_ylabel("Orphan block rate", fontfamily='sans-serif', fontsize=22)
axs.tick_params(which='major', direction="in", top=True, left=True, right=True, width=1.5, size=6, labelsize=16)
axs.tick_params(which='minor', direction="in", top=True, left=True, right=True, width=1, size=4, labelsize=16)
axs.legend(prop=font, frameon=False)
plt.show()
This produces the following output:
Does anyone know why it's not showing my minor ticks?
Thank you so much in advance!!
I believe minor ticks are visible only if there is enough space.
You may try to increase the figure size
fig, axs = plt.subplots(..., figsize=(10,10))
or decrease the font size.
Related
I am plotting 4 subplots on 1 figure with code below. When I try to plot the same plot in the notebook later just with fig I receive the same plot but with no white background, it is transparent. Any idea why it happens and what should I do to also get white background in next plot?
fig, axes = plt.subplots(figsize=(14, 10), nrows=2, ncols=2)
vec1 = np.random.randint(1,11,100)
vec2 = np.random.rand(100)
vec3 = np.random.randn(100)
vec4 = np.random.random(100)
axes[0, 0].plot(vec1, label='1')
axes[0, 1].hist(vec2, bins=20, edgecolor='k')
axes[1, 0].plot(vec3, label='3')
axes[1, 1].hist(vec4, bins=20, edgecolor='k')
axes[0][0].set_title("randint", fontsize=15)
axes[0][1].set_title("rand", fontsize=15)
axes[1][0].set_title("randn", fontsize=15)
axes[1][1].set_title("random", fontsize=15)
fig.legend(loc='upper left')
fig.suptitle("Losowe wektory", fontsize=18)
fig.subplots_adjust(left=0.1, bottom=0.05, right=0.9, top=0.9, wspace=0.15, hspace=0.35)
fig, axes = plt.subplots(figsize=(14, 10), nrows=2, ncols=2, facecolor='white')
Setting facecolor to white solves the problem, first I thought it is would be basically white and we have to set transparency to get it but it is otherwise as I can see.
I am using secondary y-axis and cmap color but when I plot together the color bar cross to my plot
here is my code
fig,ax1=plt.subplots()
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10,60), c='Lifetime1 (a)', colormap='jet_r', vmin=0, vmax=25, ax=ax1)
graph.axhline(0, color='k')
plt.xticks(rotation=90)
ax2 = ax1.twinx()
ax2.plot(df_Combine_min_select1["CumEnergy1 (kWH)"])
plt.show()
and here is my plotting
anyone can help how to solve this issue?
Thank you
When you let pandas automatically create a colorbar, you don't have positioning options. Therefore, you can create the colorbar in a separate step and provide the pad= parameter to set a wider gap. Default, pad is 0.05, meaning 5% of the width of the subplot.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
df_Combine = pd.DataFrame({'Parameter2': np.random.rand(10) * 10,
'NPV (MM €)': np.random.rand(10),
'Lifetime1 (a)': np.random.rand(10) * 25,
})
ax1 = df_Combine.plot.scatter('Parameter2', 'NPV (MM €)', marker='s', s=500, ylim=(-10, 60), c='Lifetime1 (a)',
colormap='jet_r', vmin=0, vmax=25, ax=ax1, colorbar=False)
plt.colorbar(ax1.collections[0], ax=ax1, pad=0.1)
ax2 = ax1.twinx()
ax2.plot(np.random.rand(10))
plt.show()
I'm trying to get minor ticks and gridlines plotted in all plots when using lmplot, using the code below:
sns.set(context="notebook", style='white', font_scale=2)
g=sns.lmplot(data=data ,
x="x",
y="y",
col="item", # or use rows to display xplots in rows (one on top of the other)
fit_reg=False,
col_wrap=2,
scatter_kws={'linewidths':1,'edgecolor':'black', 's':100}
)
g.set(xscale='linear', yscale='log', xlim=(0,0.4), ylim=(0.01, 10000))
for ax in g.axes.flatten():
ax.tick_params(axis='y', which='both', direction='out', length=4, left=True)
ax.grid(b=True, which='both', color='gray', linewidth=0.1)
for axis in [ax.yaxis, ax.xaxis]:
formatter = FuncFormatter(lambda y, _: '{:.16g}'.format(y))
axis.set_major_formatter(formatter)
sns.despine()
g.tight_layout()
# Show the results
plt.show()
So far, only major ticks and gridlines are shwon in all plots.
Thanks for any advice for solving this
Your code work fine for me.
I think the problem is that when the major labels are too big, matplotlib chooses not to display the minor ticks, and hence the minor grid lines. You may either change font_scale, or increase the size of your figure (see height= in lmplot())
Consider the following code with font_scale=1
tips = sns.load_dataset('tips')
sns.set(context="notebook", style='white', font_scale=1)
g = sns.lmplot(x="total_bill", y="tip", col="day", hue="day",
data=tips, col_wrap=2, height=3)
g.set(xscale='linear', yscale='log')
for ax in g.axes.flatten():
ax.tick_params(axis='y', which='both', direction='out', length=4, left=True)
ax.grid(b=True, which='both', color='gray', linewidth=0.1)
for axis in [ax.yaxis, ax.xaxis]:
formatter = matplotlib.ticker.FuncFormatter(lambda y, _: '{:.16g}'.format(y))
axis.set_major_formatter(formatter)
sns.despine()
g.tight_layout()
# Show the results
plt.show()
compare with the result using font_scale=2
I am trying to modify the x-ticks of a plot, but one of the tick labels automatically generated by matplotlib does not disappear, and the one I assign overlaps it. The code is:
ax[0].plot((zspace+1.),dndt_vs_z_9, color='blue', label=r'$M_s = 10^9$')
ax[0].plot((zspace+1.),dndt_vs_z_10, color='red', label=r'$M_s = 10^{10}$')
ax[0].plot((zspace[zspace<=2]+1.),dndt_vs_z_11[zspace<=2], color='green', label=r'$M_s = 10^{11}$')
ax[0].plot((zspace[zspace<=2]+1.),(1./2.)*dndt_vs_z_11[zspace<=2], color='black')
ax[0].plot((zspace[zspace<=2]+1.),0.65*dndt_vs_z_11[zspace<=2], color='black')
ax[0].plot(gomez_11_x,gomez_11_y,color='blue', linestyle='dashed')
ax[0].plot(gomez_10_x,gomez_10_y,color='red', linestyle='dashed')
ax[0].plot(gomez_9_x,gomez_9_y,color='green', linestyle='dashed')
#ax[0].scatter(ill_shmr_z,ill_shmr_dndw_model_11)
ax[0].set_yscale('log')
ax[0].set_xscale('log')
ax[0].set_xticks([1,2,3,4,5], minor=True)
ax[0].set_xticklabels([1,2,3,4,5], minor=True, fontsize='20')
ax[0].set_xlim([1,5])
ax[0].set_ylim([1e-2,1e1])
ax[0].legend(loc='best', fontsize='20')
ax[0].grid(b = True, which='major')
ax[0].grid(b = True, which='minor', axis='x')
ax[0].set_xlabel(r'$1+z$', fontsize='15')
ax[0].set_ylabel(r'$\frac{dN}{dt}$', fontsize='20')
and the result is:
The problem here comes from mixing major and minor ticks when using log scale. A solution in your example case would be to remove the major ticks using a NullLocator and only use the minor ticks:
A small example would be:
import matplotlib.pyplot as plt
import matplotlib.ticker
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12,7))
ax1.loglog([1,2,3,4,5])
ax1.set_xticks([1,2,3,4,5],minor=True)
ax1.set_xticklabels([1,2,3,4,5], minor=True, fontsize='20')
ax1.set_title("Reproduce problem")
ax2.loglog([1,2,3,4,5])
ax2.set_xticks([1,2,3,4,5],minor=True)
ax2.set_xticklabels([1,2,3,4,5], minor=True, fontsize='20')
ax2.xaxis.set_major_locator(matplotlib.ticker.NullLocator())
ax2.set_title("Apply fix")
plt.show()
I wrote the following code below to do the following graph:
fig, ax = plt.subplots(figsize=(8, 6))
ax.patch.set_facecolor('white')
ax.plot(df.index, df.X1.values, 'b',
label='NMA', linewidth=1.5)
ax.set_ylabel('Index')
ax2 = ax.twinx()
ax2.plot(df.index, df.Y.values, 'r--',
label='Rate', linewidth=1.5)
ax2.set_ylabel('Rate')
lines = ax.get_lines() + ax2.get_lines()
lgd = ax.legend(lines, [line.get_label() for line in lines],
loc='lower center', ncol=2, bbox_to_anchor=(0.5, -0.15),
frameon=False)
ax.set_title('Economic Rate and Index',
weight='bold')
for i in range(5):
plt.axvspan(Dates['Peak'][i], Dates['Trough'][i],
facecolor='grey', alpha=0.5)
plt.grid(False)
plt.savefig('C:\\test.pdf',
bbox_extra_artists=(lgd,), bbox_inches='tight')
I am having a hard time to reproduce this figure in a subplot (2X2). The only thing I would change in each of the subplots is the blue line (X1 in df... for X2, X3...). How can I have a 2X2 subplot of the above graph? Of Course I would only keep one legend at the bottom of the subplots. Thanks for the help.
The data is here and the "Dates" to reproduce the gray bars here.
This is how you could create a 2x2 raster with twinx each:
import matplotlib.pyplot as plt
fig, ((ax1a, ax2a), (ax3a, ax4a)) = plt.subplots(2, 2)
ax1b = ax1a.twinx()
ax2b = ax2a.twinx()
ax3b = ax3a.twinx()
ax4b = ax4a.twinx()
ax1a.set_ylabel('ax1a')
ax2a.set_ylabel('ax2a')
ax3a.set_ylabel('ax3a')
ax4a.set_ylabel('ax4a')
ax1b.set_ylabel('ax1b')
ax2b.set_ylabel('ax2b')
ax3b.set_ylabel('ax3b')
ax4b.set_ylabel('ax4b')
plt.tight_layout()
plt.show()
Result: