How to change rotation of xticks in matplotlib? - python

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)

Related

Matplotlib display grid line at bottom instead of spine

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()

How to add a colorbar right from kde plot seaborn with histograms

How can I add a colorbar right from a kde plot of seaborn jointplot with histograms on vertical and horizontal axis.
When trying this:
fig, ax = plt.subplots()
cbar_ax = fig.add_axes([.8, .25, .03, .4])
sns.jointplot(x=df["x"], y=df["y"], kind='kde', ax=ax, cbar_ax = cbar_ax, cbar=True)
histograms are not included in the image and the main figure and colorbar are overlapping.

Overplot the mean line in Python

I'd like to get two lines (red and green) with the average of my data points in green and average of my data points in red. I'm using the following code, but it's not working. It's only showing the red and green data points, without the red average line
sns.set(rc={"figure.figsize": (16, 8)})
ax = events_all_metrics[["event_name","kambi_payback"]].plot(x="event_name", style='.',use_index=False, color ='green')
events_all_metrics[["event_name","pinny_payback"]].plot(x="event_name",style='.', color='red', ax=ax)
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom='off', # ticks along the bottom edge are off
top='off', # ticks along the top edge are off
labelbottom='off')
plt.legend(loc=4, prop={'size': 15})
pinny_mean = events_all_metrics["pinny_payback"].mean()
ax.plot(pinny_mean, label='Pinny Mean', linestyle='--', color='red')
plt.show()
This is not working because your pinny_mean is a single value in y. plot needs points in y and x. In this case I recommend you use plt.axhline instead of plot. It plots a line of constant y that covers the whole range in x. For your example:
plt.axhline(y=pinny_mean, label='Pinny Mean', linestyle='--', color='red')

Setting the X Axes Limit in Matplotlib 1.4.3

I am trying to zoom in on a section of my plot. I used the following code to produce the high level plot below.
fig = poll_df.plot('Start Date', 'Difference',figsize=(12,4),marker='o',linestyle='-',color='purple')
# Now add the debate markers
plt.axvline(x=403+2, linewidth=4, color='grey')
plt.axvline(x=403+10, linewidth=4, color ='grey')
plt.axvline(x=403+21, linewidth=4, color='grey')
plt.show()
The vertical grey bars are in the right locations and I want to zoom in on the plot (basically to show the month of October). I modified the plot to add the xlim parameters as below.
fig = poll_df.plot('Start Date', 'Difference',figsize=(12,4), marker='o',linestyle='-',color='purple',xlim=(403,433))
# Now add the debate markers
plt.axvline(x=403+2, linewidth=4, color='grey')
plt.axvline(x=403+10, linewidth=4, color ='grey')
plt.axvline(x=403+21, linewidth=4, color='grey')
plt.show()
However, this gives me a totally different plot (see below). I have tried all sorts of variations and still can't seem to get it to work. It looks as if the vertical bars would be in the right places if the axis labels reflected the month of October.
Why did the plot not rescale the x labels?

Increasing the space for x axis labels in Matplotlib

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)

Categories

Resources