This question already has answers here:
How to set ticks on Fixed Position , matplotlib
(2 answers)
How to force integer tick labels
(4 answers)
How to force matplotlib to show values on x-axis as integers
(2 answers)
In Matplotlib, what axis attribute specifies the spacing between ticks? [duplicate]
(1 answer)
Closed 1 year ago.
I want to change values across the x- & y-axes in a plot.
import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['figure.figsize'] = 7,6
x = range(1,20)
y = list(np.random.rand(19) * 100)
fig = plt.figure()
ax = fig.add_axes([0.01,0.1,1,1])
ax.plot(x,y,marker = 'o')
I want to change x-axis values that are appearing as decimals. Instead, I want to customize it and show values like 2,4,6 .. 18.
Any suggestions will be a kind help.
Thank you
Related
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.
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')
This question already has answers here:
Prevent scientific notation
(1 answer)
How to prevent numbers being changed to exponential form in a plot
(6 answers)
turn off scientific notation for matplotlib [duplicate]
(1 answer)
matplotlib remove axis label offset by default
(2 answers)
Closed 1 year ago.
The image speaks for itself:
I want matplotlib to explicitly print the full length y-labels (8 digits total with 6 decimals after the point). But it keeps splitting them into the bias (which can be seen in the top left corner) and the remainder.
I tried disabling the autoscale and setting manual ylims, doesn't help.
You can retrieve the default y-ticks using plt.gca().get_yticks() and then use plt.gca().set_yticklabels to set them to your desired format (documentation for .set_yticklabels is here and documentation for .gca is here).
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
## reproduce your curve
x = np.linspace(31.5,34,500)
y = 3.31*(10**-5)*x**2 - 2.22*(10**-3)*x - 3.68*10**1
plt.scatter(x,y,marker='.')
## retreieve and set yticks
yticks = plt.gca().get_yticks()
plt.gca().yaxis.set_major_locator(mticker.FixedLocator(yticks))
plt.gca().set_yticklabels([f"{y:.6f}" for y in yticks])
plt.show()
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()
This question already has answers here:
Overlapping axis tick labels in logarithmic plots
(2 answers)
Matplotlib: setting x-limits also forces tick labels?
(1 answer)
Closed 5 years ago.
I'm plotting with matplotlib. When I set the x-scale to 'log' and change the tick labels and formatting to display linearly, the logspace tick labels don't go away, and I end up with two sets of xticklabels (one linear and one logspace).
This didn't happen on another machine, so I think it is version-specific? Right now I'm working in Jupyter Notebook with matplotlib 2.0.2 and python 3.6.1.
MWE:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
%matplotlib inline
fig, ax = plt.subplots(1, 1)
xmin = 5
xmax = 50
ax.set_xscale('log')
ax.set_xticklabels(np.logspace(np.log10(xmin), np.log10(xmax), num=6))
ax.set_xticks(np.logspace(np.log10(xmin), np.log10(xmax), num=6))
ax.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
ax.set_xlim([xmin, xmax])