Hide some x axis labels, only keep 1 matplotlib - python

I have a plot with multiple curves, and they have the same x axis but somehow they are overlapping so the x axis is unreadable. I would like to only keep the x axis label for df.boxplot while hiding axis labels coming from df_median.plot(). Plots are done through pandas.
I tried something like this with the intention of hiding the x axis labels for a only
df.boxplot(column=['vals'], by='date', ax=axes[0], rot=45, showfliers=False, showmeans=True, whis=0)
axes[0].axhline(y=df.vals.mean(), color='r', linestyle='-')
a = df_median.plot(y='vals', ax=axes[0], label='7 day')
a.xaxis.set_visible(False)
However this just removed x axis labels all together.

Related

In a bar plot: For many observations the x axis is not readable

I have 279 observations, I would like to plot them in a bar plot. the x axis values are the names of the observations and y axis are Deltas: numbers. The problem is the names are not readable. Is there a way to plot 279 on one plot where I can read the x axis for this huge number of observations.
fig = plt.figure(figsize=(25, 20))
ax = fig.add_axes([0,0,1,1])
y_pos = np.arange(len(Names))
plt.xticks(y_pos, Names, color='white', rotation=45, fontweight='bold', fontsize='17',horizontalalignment='right')
ax.bar(Names,Deltas)

How to add x and y labels for each individual plot subplots when x and y axis is shared?

I am creating a 3x3 grid of subplots with shared x and y axis in jupyter notebook.
fig, ((ax1,ax2,ax3), (ax4,ax5,ax6), (ax7,ax8,ax9)) = plt.subplots(3,3, sharex=True, sharey=True)
x = np.linspace(0, 2*np.pi, 400)
y = np.sin(x**2)
ax5.plot(x,y,'-')enter code here
Now when I try to make x and y labels for each individual subplot visible through following code, nothing happens.
for ax in plt.gcf().get_axes():
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_visible(True)
How do I get x and y labels for each subplot when x and y axis are shared?
As per the documentation:
When subplots have a shared x-axis along a column, only the x tick labels of the bottom
subplot are created. Similarly, when subplots have a shared y-axis along a row,
only the y tick labels of the first column subplot are created.
To later turn other subplots' ticklabels on, use tick_params.
fig, axs = plt.subplots(3,3, sharex=True, sharey=True, constrained_layout=True)
for ax in axs.flat:
ax.tick_params(labelbottom=True, labelleft=True)

Align x and y axis with twinx twiny in log scale

I want to create a plot with two x axis and also two y axis. I am using twiny and twinx to do it. The secondary axis are just a rescaling of the original ones, so I'm applying a transformations to get the ticks. The problem is that I am in log scale, so the separation between the ticks does not match between the original and the twin ax. Moreover, the second x axis has other values that I don't want.
Let's follow an example to explain better:
#define the transformations I need
h=0.67
def trasf_log(y):
y_ = 10**y
return y_/h
def trasf_sigma(x):
return 1.68/x
#plot in log scale and with ticks that I choose
fig,ax = plt.subplots(1)
ax.plot(x,y0)
ax.set_ylim(1.0,2.4)
ax.set_xlim(0.6,5)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xticks([0.6,0.8,1,2,3,4])
ax.set_yticks([1.0,1.2,1.4,1.6,1.8,2.0,2.2,2.4])
ax.xaxis.set_major_formatter(ScalarFormatter())
ax.yaxis.set_major_formatter(ScalarFormatter())
ax.ticklabel_format(axis='both', style='plain')
ax.set_xlabel(r'$\nu$', fontsize=20)
ax.set_ylabel(r'$\log_{10}Q$', fontsize=20)
ax.tick_params(labelsize=15)
#create twin axes
ax1 = ax.twinx()
ax1.set_yscale('log')
ymin,ymax=ax.get_ylim()
ax1.set_ylim((trasf_log(ymin),trasf_log(ymax)))
ax1.set_yticks(trasf_log(ax.get_yticks()))
ax1.yaxis.set_major_formatter(ScalarFormatter())
ax1.ticklabel_format(axis='y', style='plain')
ax1.tick_params(labelsize=15,labelleft=False,labelbottom=False,labeltop=False)
ax1.set_ylabel(r'$Q$', fontsize=20)
ax2 = ax.twiny()
ax2.set_xscale('log')
xmin,xmax=ax.get_xlim()
ax2.set_xlim((trasf_sigma(xmin),trasf_sigma(xmax)))
ax2.set_xticks(trasf_sigma(ax.get_xticks()))
ax2.xaxis.set_major_formatter(ScalarFormatter())
ax2.ticklabel_format(axis='x', style='plain')
ax2.tick_params(labelsize=15,labelleft=False,labelbottom=False,labelright=False)
ax2.set_xlabel(r'$\sigma $', fontsize=20)
ax.grid(True)
fig.tight_layout()
plt.show()
This is what I get:
The values of the new x and y axis are not aligned with the original ones. For example, on the two x axis the values 1 and 1.68 should be aligned. Same thing for the y axis: 1.2 and 23.7 should be aligned.
Moreover, I don't understand where the other numbers on the second x axis are coming from.
I tried already applying Scalar Formatter to each axis with 'plain' style, but nothing changes.
I also tried using secondary_axis, but I could not find a solution as well.
Anyone knows a solution?

Matplotlib transparent face settings

My goal is to make a matplotlib barchart that has only the label names on a single axis, then bars, and then the value of those bars at the top like this. However, I want to be able to embed an image like this online and want the background to be transparent. But when I savefig as transparent=True it comes out like this There are these lines in the background that are very distracting and the names of my y labels become transparent as well which I don't want.
I just need help gaining more control over transparency parameters.
fig, ax = plt.subplots(figsize=(8, 12), frameon=False)
# x dummy data
x = prez_counts['presidents']
# y dummy data
y = prez_counts['occurence']
# make facecolor transparent
ax.set_facecolor('w')
ax.patch.set_alpha(0)
# plot bar plot
ax.barh(x,y,color=sns.color_palette("gnuplot_r", len(x)), alpha=0.7)
# remove xaxis ticks
ax.get_xaxis().set_visible(False)
# add x values of y to end of bars
for i, v in enumerate(y):
ax.text(v + .5, i - .20, str(v), fontsize=(8))
sns.despine(left=True, bottom=True, right=True, top=True)
plt.tight_layout()
plt.savefig('../3_output/test.png', transparent=True)
I would like the output to be the same plot, just without the lines in the background and without clear/translucent y labels.

How to display axis tick labels over plotted values using matplotlib and seaborn?

I am using matplotlib and seaborn in order to scatter plot some data contained in two arrays, x and y, (2-dimensional plot). The issue here is when it comes to displaying both axis labels over the data, because plotted data overlaps the values so the are unseen.
I have tried different possibilities such as resetting the labels after the plot is done and setting them later, or using annotation marks. Anyways any of those options worked for me...
The piece of code I am using to generate this scatter plot is:
sns.set_style("whitegrid")
ax = sns.scatterplot(x=x, y=y, s=125)
ax.set_xlim(-20, 20)
ax.set_ylim(-20, 20)
ax.spines['left'].set_position('zero')
ax.spines['left'].set_color('black')
ax.spines['right'].set_color('none')
ax.yaxis.tick_left()
ax.spines['bottom'].set_position('zero')
ax.spines['bottom'].set_color('black')
ax.spines['top'].set_color('none')
ax.xaxis.tick_bottom()
values = ax.get_xticks()
ax.set_xticklabels(["{0:.0%}".format(x/100) for x in values])
values = ax.get_yticks()
ax.set_yticklabels(["{0:.0%}".format(y/100) for y in values])
ax.tick_params(axis='both', which='major', labelsize=15)
ax.grid(True)
The generated plot is as follows:
But the desired output should be something like this:
Thank you in advance for any advice or help!
You need two things: zorder and a bold weight for the ticklabels. The zorder of scatter points needs to be lower than that of the tick labels so that the latter appear on the top. 'fontweight': 'bold' is to have boldfaced tick labels.
The axis appears shifted off the 0 but that is because you did not provide any data. So I have to choose some random data
# import commands here
x = np.random.randint(-100, 100, 10000)
y = np.random.randint(-100, 100, 10000)
ax = sns.scatterplot(x=x, y=y, s=125, zorder=-1)
# Rest of the code
values = ax.get_xticks()
ax.set_xticklabels(["{0:.0%}".format(x/100) for x in values], fontdict={'fontweight': 'bold'})
values = ax.get_yticks()
ax.set_yticklabels(["{0:.0%}".format(y/100) for y in values], fontdict={'fontweight': 'bold'})
ax.tick_params(axis='both', which='major', labelsize=15, zorder=1)
ax.grid(True)

Categories