X axis for plt plot python is cluttered together [duplicate] - python

This question already has answers here:
Matplotlib showing x-tick labels overlapping
(3 answers)
Closed 11 months ago.
plt.figure(figsize=(4,4))
aapl_data.plot.line(x='Date',y='Adj Close',title='test')
plt.ylabel('Adj Close')plt.show()
How do i declutter the X axis. I tried using figsize in the code but it does not do anything

Better show the whole code. Since I'm not sure if you have such a string: ax = plt.axes()
ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))

Try to formate the date
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%b'))

There can be two solutions to this problem.
Increasing the width of the window. This can be achieved by:
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(40,4))
fig.add_subplot(1,1,1).plot([1,2,3], [1,2,3])
plt.show()
Making the labels vertical rather than horizontal. This can be done by:
plt.xticks(range(10), rotation='vertical')

Related

Undesired shadow in matplotlib pyplot [duplicate]

This question already has answers here:
Convert dataframe index to datetime
(4 answers)
Plot the x-axis as a date
(2 answers)
Plotting dates on the x-axis
(4 answers)
Closed 5 months ago.
I'm trying to plot some data for school project. However an ugly shadow appears when I do so. I have no clue of what it can be.
Here is my code:
index_labels = np.empty(len(smoothed), dtype=object)
for i in range(len(index_labels)):
index_labels[i] = ""
if i%365 == 0:
index_labels[i] = 2015 + int(i//365)
plt.scatter(smoothed.index, smoothed.national, label='PV load factor rolling mean over 24h.')
plt.plot(smoothed.index, sin_ref, color='red', label='Sinusoidal reference')
ax = plt.gca()
ax.set_xticklabels(index_labels)
# plt.legend()
plt.show()
and here is the different variables used so you have an idea:
and a zoom on the plot :
Thanks to all of you! Greetings :)
Solution from #BigBen:
from matplotlib.ticker import MultipleLocator
plt.scatter(smoothed.index, smoothed.national, label='PV load factor rolling mean over 24h.')
plt.plot(smoothed.index, sin_ref, color='red', label='Sinusoidal reference')
ax = plt.gca()
ax.xaxis.set_major_locator(MultipleLocator(730))
plt.show()
Multiple has a very good name: it only shows the label for the multiple of n.
EDIT: as find later, matplotlib do auto axis labeling for dates. Only problem was that column was recognized as string. pandas.to_datetime allow you to convert it back to pandas datetime type.

How to plot y-axis to the opposite side? [duplicate]

This question already has answers here:
matplotlib y-axis label on right side
(4 answers)
Closed 2 years ago.
I have this chart below:
I would want the y-axis for the lower subplot to be plotted to the opposite side since that would make more sense. Is there a method for this? The ax.invert_yaxis() simply inverts the labels.
Note: For the curious, I simply used .invert_xaxis() to plot inverted bars.
I guess, what you are looking for is
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
of an axis object.
So with #meTchaikovsky's MVE code, you'll get
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(1,10,10)
y0 = np.random.randint(0,30,size=10)
fig,ax = plt.subplots(nrows=2,ncols=1,figsize=(8,6))
ax[1].set_xlim(0,30)
ax[0].barh(x,y0,color='violet')
ax[0].set_ylabel("Y-Axis")
ax[1].set_xlim(30,0)
ax[1].barh(x,y0,color='deepskyblue')
ax[1].yaxis.set_ticks_position("right")
ax[1].yaxis.set_label_position("right")
ax[1].set_ylabel("Y-Axis")
plt.show()

How to get rid of all ylabels of all subplots.[matplotlib] [duplicate]

This question already has an answer here:
Setting axis labels for histogram pandas
(1 answer)
Closed 2 years ago.
I would like to know how to get rid of all labels of all subplots. I have a dataframe consisting of 37 columns. Then, to make histograms for them, I wrote this code.
p_variables.plot.hist(subplots=True,layout=(5,8),figsize=(20,20),sharex=False,ylabel="")
plt.show()
I expected that all of ylabels of subplots were invisible by setting ylabel="". However, they do not disappear. Could someone give me idea how to solve this?
The output is below. I would like to get rid of Frequency labels.
You'll need to iterate over the returned axes and set the ylabel to "" explicitly.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame(np.random.rand(40, 5), columns=list("ABCDE"))
axes = df.plot.hist(subplots=True,layout=(5,8),figsize=(20,20),sharex=False)
for ax in axes.flatten():
ax.set_ylabel("")
plt.show()

matplotlib: place legend labels where each trace intercepts the right-hand y-axis [duplicate]

This question already has answers here:
How to annotate end of lines using python and matplotlib?
(3 answers)
Closed 3 years ago.
I have multiple lines plotted on an xy scatter plot
There are more than the number of colours in my palette, which means the colours start cycling.
I have played with using other palettes but the visibility suffers.
An idea I would like to explore now is to add the legend labels at the point where each line intercepts the right-hand y-axis.
Something like this:
Is this possible to achieve with matplotlib and/or seaborn?
Quick one, with use of the other answer to this question
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
names = ['foo', 'bar', 'foobar']
N_size = 100
fig, ax = plt.subplots(1, 1)
df = pd.DataFrame(map(lambda x: pd.Series(np.cumsum(np.random.rand(N_size) - 0.5), name=x), names)).T
df.plot(ax=ax)
ax2 = ax.twinx()
ax2.set_ylim(ax.get_ylim())
ax2.set_yticks([df[col].iloc[-1] for col in df.columns])
ax2.set_yticklabels(df.columns)
plt.show()

Moving all x-axis tick labels a few pixels to the right (aligning rotated labels) [duplicate]

This question already has an answer here:
Moving matplotlib xticklabels by pixel value
(1 answer)
Closed 5 years ago.
I'm doing a bar plot with long labels, which I've rotated 45 degrees and set to be right-aligned. However, the tick labels are still a bit away from the ticks, making the plot look strange. How do move all the labels a few points to the right?
Here is my current code:
import seaborn as sns
import pylab as plt
plt.figure()
ax = sns.barplot(x="item", y="dist", hue="dset", data=df)
plt.xticks(rotation=45, ha='right')
plt.tight_layout()
EDIT: Please take look at the right-aligned subplot in stackoverflow.com/a/14854007/1452257 for an example. I can also copy the code/image to this post if you prefer.
From ImportanceOfBeingErnest's answer here, I got the following on translating tick labels in a general, arbitrary way:
import matplotlib.transforms as mtrans
# ...
trans = mtrans.Affine2D().translate(20, 0)
for t in ax.get_xticklabels():
t.set_transform(t.get_transform()+trans)

Categories