Disappearing x-axis in pandas/matplotlib when trying to alter xticklabels [duplicate] - python

This question already has answers here:
Getting empty tick labels before showing a plot in Matplotlib
(2 answers)
Closed 2 years ago.
I am seeking a better understanding of python plotting routines in pandas/matplotlib that cause xticklabels to disappear when formatting is attempted. To demonstrate, here is some basic code to recreate the problem:
#Create dummy variables x and y in a dataframe and plot in a scatter plot with the xticklabels rotated 35 degrees
data={'x':[1111,2222,3333,4444], 'y':[1211,1322,1260,5555]};
df=pd.DataFrame(data=data);
ax1=df.plot('x', 'y', kind='scatter', c='lightblue', s=50, edgecolors='black')
#Create dummy variables x and y in a dataframe and plot in a scatter plot with the xticklabels rotated 35 degrees
data={'x':[1111,2222,3333,4444], 'y':[1211,1322,1260,5555]};
df=pd.DataFrame(data=data);
ax1=df.plot('x', 'y', kind='scatter', c='lightblue', s=50, edgecolors='black')
This generates a generic plot with labeled x- and y- axes and x- and y- ticklabels.
(generic x-y scatter plot with default axis and tickmark labels)
Now, if I want to rotate the xticklabels and horizontally align them to the right, that is where I run into the disappearing xticklabels:
#I would like to change the angle of rotation of the xticklabels of the ax1 handle.
labels=ax1.get_xticklabels()
print(labels)
ax1.set_xticklabels(labels, rotation=40)
ax1.set_xticklabels(labels, ha="right")
Now the xticklabels have disappeared. I've added a line to print the xticklabels because most examples perform the set_xticklabels when custom labels are being affixed to the plot. I just want to use what was already plotted. I think that the problem may lie in the contents of the 'labels' variable that I populated with get_xticklabels, but I am having trouble connecting the dots here. Any help understanding this will be greatly appreciated!

If you don't need pandas, you could just do this.
import matplotlib.pyplot as plt
data = {'x': [1111, 2222, 3333, 4444], 'y': [1211, 1322, 1260, 5555]};
fig, ax = plt.subplots()
ax.scatter(data['x'], data['y'], ec='k', fc='lightblue', s=50)
plt.xticks(rotation=45, ha='right')
plt.show()

Related

Selectively marking horizontal regions in Seaborn Plot (Python) [duplicate]

This question already has answers here:
How to highlight specific x-value ranges
(2 answers)
Closed 1 year ago.
I went through the examples in the matplotlib documentation, but it wasn't clear to me how I can make a plot that fills the area between two specific vertical lines.
For example, say I want to create a plot between x=0.2 and x=4 (for the full y range of the plot). Should I use fill_between, fill or fill_betweenx?
Can I use the where condition for this?
It sounds like you want axvspan, rather than one of the fill between functions. The differences is that axvspan (and axhspan) will fill up the entire y (or x) extent of the plot regardless of how you zoom.
For example, let's use axvspan to highlight the x-region between 8 and 14:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, alpha=0.5, color='red')
plt.show()
You could use fill_betweenx to do this, but the extents (both x and y) of the rectangle would be in data coordinates. With axvspan, the y-extents of the rectangle default to 0 and 1 and are in axes coordinates (in other words, percentages of the height of the plot).
To illustrate this, let's make the rectangle extend from 10% to 90% of the height (instead of taking up the full extent). Try zooming or panning, and notice that the y-extents say fixed in display space, while the x-extents move with the zoom/pan:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, ymin=0.1, ymax=0.9, alpha=0.5, color='red')
plt.show()

Matplotlib squeezing x labels [duplicate]

This question already has answers here:
Rotate tick labels in subplot (Pyplot, Matplotlib, gridspec)
(3 answers)
Closed 2 years ago.
I'm trying to plot a lot a data points and the X axis is timestamps. My problem is that for some length Matplotlib automatically squeezes them together and you cannot read the x axis, as shown in the pic:
How can I prevent this from happening? I'm trying to save that plot automatically with savefig(). It is saved to a PNG.
you can specify the X-Ticks with following:
import matplotlib.pyplot as plt
plt.plot(x_values, y_value)
plt.xticks([0,5,10])
The Plot will have less ticks.
WIthout the x-ticks:
With x-ticks:
I found the answer here on the matplotlib site:
https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html
fig, ax = plt.subplots()
ax.plot(date, r.close)
# rotate and align the tick labels so they look better
fig.autofmt_xdate()
# use a more precise date string for the x axis locations in the
# toolbar
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.set_title('fig.autofmt_xdate fixes the labels')

Shift matplotlib axes to match eachother

I am looking to overlay a scatter plot with a boxplot in matplotlib. I have created the chart but the x axes do not match--leading to the scatter plot showing dots that are shifted 1 tick to the left of the x axis for the boxplot. Below is my code.
fig, ax = plt.subplots()
ax.scatter(traits_5, data_df[traits_5].loc[y])
ax = greats_df[traits_5].boxplot ( showfliers=False , column=traits_5)
plt.ylabel ( 'Percentile Score' )
plt.title ( "Distribution of The Greats' Scores" )
ax.yaxis.set_major_formatter(mtick.PercentFormatter(1))
plt.show ()
Is it possible that the error is coming from the two different methods of plotting the data? I use matplotlib to plot the scatter and pandas to plot the boxplot. Matplotlib was plotting the rows on the xaxis, whereas I wanted the columns to be plotted along the x axis.
See outputted image below from above code.
Hard to investigate without having access to data, but if you just translate the x coordinates of your scatter plot, it should work:
ax.scatter([x+1 for x in traits_5], data_df[traits_5].loc[y])

seabon catplot: change position on x axis [duplicate]

This question already has answers here:
How to add axis offset in matplotlib plot?
(2 answers)
Closed 4 years ago.
I am plotting two seaborn categorical plots (pointplot and swarmplot) on top of each other and just can't figure out how I can change the x axis position of one of them (i.e. the swarm plot in my particular case) so that instead of overlapping the plots are 'side by side' (i.e. ideally I want to have the individual data points to the right of the mean and ci).
Here's the code to produce the plot:
import seaborn as sns
# set style and font size
sns.set(style='white', rc={'figure.figsize':(6,6)}, font_scale=1.3)
# plot means as points with confidence intervals
a = sns.pointplot(x='Group',
y='RT',
data=data,
estimator= np.mean,
capsize=.2,
join=False,
color='black',
size=12)
# plot individual data points as swarmplot
b = sns.swarmplot(x='Group',
y='RT',
data=data,
size=8,
alpha=0.8)
You can feed the axis handle to the sns.
I am not sure whether this is what do you want!
import seaborn as sns
sns.set(style="whitegrid")
tips = sns.load_dataset("tips")
fig,ax =plt.subplots(1,2,figsize=(15,7))
sns.swarmplot(x="day", y="total_bill", data=tips,
ax= ax[1])
sns.pointplot(x='day',
y='total_bill',
data=tips,
estimator= np.mean,
capsize=.2,
join=False,
color='black',
size=12,ax=ax[0])

How to put line plot and scatter plot on the same plot in? [duplicate]

This question already has answers here:
graphing multiple types of plots (line, scatter, bar etc) in the same window
(2 answers)
Python equivalent to 'hold on' in Matlab
(5 answers)
Closed 5 years ago.
I'm trying to plot scatter with over lined line plot. I have two sets of data and if I plot both of them as scatter plots it works, but if I try to plot the second one as a line graph (connected scatter plot), it won't even show.
plt.scatter(column1,column2,s=0.1,c='black')
plt.plot(column3,column4, marker='.', linestyle=':', color='r',)
(I tried using plt.scatter, I tried changing the markers and linestyle, tried without these as well and I still can't get it to work, I sometimes get the dots, but once I want them to be connected they disappear or nothing happens.)
plt.gca().invert_yaxis()
plt.show()
That's what I get:
Plot 1
matplotlib simply overlays plot commands in the called order as long as you do not create a new figure.
As an example, try this code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(19680801)
N = 100
x = 0.9 * np.random.rand(N)
y = 0.9 * np.random.rand(N)
plt.scatter(x, y, c='green')
plt.plot(np.linspace(0, 1, 10), np.power(np.linspace(0, 1, 10), 2), c= "red", marker='.', linestyle=':')
plt.gca().invert_yaxis()
plt.show()

Categories

Resources