How to change xticks with matplotlib? [duplicate] - python

This question already has answers here:
Change x-axis ticks to custom strings [duplicate]
(2 answers)
Closed 3 years ago.
I want to change xticks on a plot with matplotlib, say replacing for instance with a string. According to matplotlib manual https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.xticks.html I did the following code :
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(10)
y=x**2
plt.figure()
plt.plot(x,y)
locs, labels=plt.xticks()
new_xticks=['test' for d in locs]
plt.xticks(new_xticks, rotation=45, horizontalalignment='right')
The problem is when I do this, ticks on x axis are not modified, and I get the following error
ConversionError: Failed to convert value(s) to axis units: ['test',
'test', 'test', 'test', 'test', 'test', 'test']
EDIT : I want to have the ticks at the same place of the original plot, which x axis don't go beyond min and max value, as in the following picture :
Thanks in advance for your help !
EDIT2 : its not a duplicate as I do it directly without using subplots

Do something like this:
import matplotlib.pyplot as plt
import numpy as np
x=np.arange(10)
y=x**2
plt.figure()
plt.plot(x,y)
locs, labels=plt.xticks()
x_ticks = []
new_xticks=['test' for d in locs]
plt.xticks(locs,new_xticks, rotation=45, horizontalalignment='right')
plt.show()
Output:

You are modifying the ticks. But the ticks need to be numbers. If you want to modify the tick-labels you can do so via
plt.xticks(locs, new_xticks)

Related

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

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

Question about mapping x-axis values in matplotlib [duplicate]

This question already has answers here:
Plot some numbers in x axis
(3 answers)
plot with custom text for x axis points
(3 answers)
Force python axis to show specific numbers
(2 answers)
Closed 1 year ago.
I am starting to use the matplotlib library to generate simple graphs. In one of my tests something happens to me that does not allow me to obtain the graph that I expect. Coming to the point, I have two value arrays (circle and g) and I would like to join each of their values. The problem comes when I input the x-axis values. I would like only the values of my array g to be on the x axis, but the following happens:
In my code I have the following:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
circle = [0.002,0.013,0.035]
g = [5,25,50]
ax.scatter(g[0], circle[0], color = 'g', marker = "o")
x = np.array([0,1,2,3])
my_xticks = [0,5,25,50]
plt.xticks(x, my_xticks)
plt.show()
Could someone help me fix this?
The problem was that when calling plt.xticks(), you passed [0, 1, 2, 3] as the x-tick values, and you passed the tick values you really wanted as the tick labels. Instead, pass the tick values you want as the first argument, and omit the second argument. The tick labels will be strings of the tick values by default.
import matplotlib.pyplot as plt
circle = [0.002, 0.013, 0.035]
g = [5, 25, 50]
my_xticks = [0] + g
fig, ax = plt.subplots()
ax.scatter(g, circle, color='g', marker='o')
plt.xticks(my_xticks)
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()

How to change axis labels in matplotlib? [duplicate]

This question already has answers here:
Modify tick label text
(13 answers)
Closed 3 years ago.
I have the following piece of code which creates a simple plot with matplotlib (python 3.6.9, matplotlib 3.1.2, Mac Mojave):
import numpy as np
import matplotlib.pyplot as plt
plt.imshow(np.random.random((50,50)))
plt.show()
The created plot is as expected:
Now, in order to relabel the xtick/ytick labels I am using the following code
import numpy as np
import matplotlib.pyplot as plt
plt.imshow(np.random.random((50,50)));
ticks, labels = plt.xticks()
labels[1] = '22'
plt.xticks(ticks, labels)
plt.show()
where I expect the second label to be replaced by '22', but everything else stays the same. However, I get the following plot instead:
There is some unexpected white area in the left part of the plot
All the other labels have vanished.
How to do it correctly?
Just as a reminder: I want to get the exact same result as the original image (first plot), ONLY with one of the lables changed.
This question has been asked before, one example is here. But the answer does not seem to work. Here is the code
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
plt.imshow(np.random.random((50,50)))
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[1] = 'Test'
ax.set_xticklabels(labels)
plt.show()
which creates an image as follows:
which does not show the white area anymore, but still the other labels are not shown.
Create axes using subplots, so that you can have set_xticklabels method, so you can update the labels.
You need to use, canvas.draw() to get the values.
import numpy as np
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
ax.imshow(np.random.random((50,50)));
fig.canvas.draw()
#labels = ['-10','0','22','20','30','40'] or
labels[2]=22
ax.set_xticklabels(labels)
plt.show()
Output:
Hope this is what you need!

Categories