How to remove ticklabels on a histogram with log scale - python

The following code does not remove yticklabels while it should since there is ax.set_yticklabels([]).
import numpy as np
import matplotlib.pyplot as plt
data = np.random.standard_normal(10)
fig = plt.figure()
ax = plt.axes()
ax.hist(data)
ax.set_yscale('log')
ax.set_yticklabels([])
Note: if changing 10 by 100 in data = np.random.standard_normal(10), the yticklabels are correctly removed...
Is this a bug to report? If so, how (and where) to report it?
Is there another way to remove those yticklabels?
Many thanks for your help!

you can hide like below:
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)

Related

Change the tick frequency on the x axis using a for loop [duplicate]

I do have a question with matplotlib in python. I create different figures, where every figure should have the same height to print them in a publication/poster next to each other.
If the y-axis has a label on the very top, this shrinks the height of the box with the plot. So I use MaxNLocator to remove the upper and lower y-tick. In some plots, I want to have the 1.0 as a number on the y-axis, because I have normalized data. So I need a solution, which expands in these cases the y-axis and ensures 1.0 is a y-Tick, but does not corrupt the size of the figure using tight_layout().
Here is a minimal example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0,1,num=11)
y = np.linspace(1,.42,num=11)
fig,axs = plt.subplots(1,1)
axs.plot(x,y)
locator=MaxNLocator(prune='both',nbins=5)
axs.yaxis.set_major_locator(locator)
plt.tight_layout()
fig.show()
Here is a link to a example-pdf, which shows the problems with height of upper boxline.
I tried to work with adjust_subplots() but this is of no use for me, because I vary the size of the figures and want to have same the font size all the time, which changes the margins.
Question is:
How can I use MaxNLocator and specify a number which has to be in the y-axis?
Hopefully someone of you has some advice.
Greetings,
Laenan
Assuming that you know in advance how many plots there will be in 1 row on a page one way to solve this would be to put all those plots into one figure - matplotlib will make sure they are alinged on axes:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0, 1, num=11)
y = np.linspace(1, .42, num=11)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2})
ax1.plot(x,y)
ax2.plot(x,y)
locator=MaxNLocator(prune='both', nbins=5)
ax1.yaxis.set_major_locator(locator)
# You don't need to use tight_layout and using it might give an error
# plt.tight_layout()
fig.show()

matplotlib: how to simultaneously change tick position and figure shape

I'm plotting a figure and hope to set the figure shape and tick positions. But I find that I cannot do the two things together. For example, if I use the following code:
import matplotlib
import matplotlib.pyplot as plt
ls = range(0,10)
fig, ax = plt.subplots()
# set figure shape
plt.figure(figsize=(10,5))
plt.ylim([0,10])
plt.plot(ls)
figname = 'aaa.jpg'
# set ytick positions
ax.set_yticks([1,3,5,7,9])
plt.savefig(figname,format='jpg')
Then I get the following figure.
The shape is correct. But the ytick is not changed by the code line ax.set_yticks([1,3,5,7,9]).
Then I try the following code (i.e. move the sentence plt.figure(figsize=(10,5)) to the beginning of the program):
import matplotlib
import matplotlib.pyplot as plt
# set figure shape
plt.figure(figsize=(10,5))
ls = range(0,10)
fig, ax = plt.subplots()
plt.ylim([0,10])
plt.plot(ls)
figname = 'aaa.jpg'
# set ytick position
ax.set_yticks([1,3,5,7,9])
plt.savefig(figname,format='jpg')
Then I get the following figure:
The ytick is correct. Yicks appear in positions [1,3,5,7,9]. However, the figure shape is not the shape I set.
How to do the two things together?
Thank you all for helping me!!!
you can set the figsize in the subplot function instead.
what went wrong in the first graph:
plt.figure(figsize=(10,5))
the above line of code is creating a new figure on which your graph is being plotted, the 'ax' on which you are setting the y ticks is related to a subplot which is different.
ls = range(0,10)
fig, ax = plt.subplots(figsize=(10,5))
ax.set_yticks([1,3,5,7,9])
ax.set_xticks([1,3,5,7,9])
plt.grid()
plt.plot(ls)
The plot is showing exactly what you're trying to do

Matplotlib: Saved files in a loop aren't the same as in show()

My program shows the correct graph in the plt.show() pop up but not in the fig.savefig one. I'm quite new to python so apologies if it is something simple.
I'm using python 2.7.10, windows (10).
import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt('strike_details.txt') #, skip_header= 0
header= 3
information=10000
width = 5
files = 16
types = 4
length = information + header
frames = data[header:length,0]
fig= plt.figure()
plt.grid(True)
for i in range(0,int(files)):
density=data[(header+i*length):(length+i*length),4]
plt.plot(frames,density, label=data[i*length+1][2])
for j in range (0,files/types):
if i==(types*(j+1)-1):
plt.legend(loc='best')
plt.xlabel('$Frames$', fontsize=22)
plt.ylabel('$Density$', fontsize=22)
fig.savefig(str(data[j*length+1][0])+'_'+str(data[j*length+1][1])+'_'+str(data[j*length+1][2])+'.png',format='png', dpi=fig.dpi)
plt.show()
plt.clf()
The program produces four files with different file names but they're all of the first group you see in the plt.show pop up.
If I missed out anything important let me know.
Thanks,
Lio
I think this is due to mixing the API-style and interactive-styles of matplotlib. When you call plt.show() the link between the active figure and fig is broken, and so you continue to output the first figure you created. I can reproduce this problem with this minimal example:
import matplotlib.pyplot as plt
fig = plt.figure()
for n in range(0,10):
plt.plot(list(range(0,n)))
fig.savefig('test%d.png' % n)
plt.show()
plt.clf()
If you remove the show() the issue goes away.
The correct way to do this is to access the current interactive figure via plt.gcf():
plt.gcf().savefig(...)
Alternatively, you can workaround it by recreating the figure object on each loop:
for i in range(0,int(files)):
fig= plt.figure()
plt.grid(True)
...

matplotlib - How can I use MaxNLocator and specify a number which has to be in an axis?

I do have a question with matplotlib in python. I create different figures, where every figure should have the same height to print them in a publication/poster next to each other.
If the y-axis has a label on the very top, this shrinks the height of the box with the plot. So I use MaxNLocator to remove the upper and lower y-tick. In some plots, I want to have the 1.0 as a number on the y-axis, because I have normalized data. So I need a solution, which expands in these cases the y-axis and ensures 1.0 is a y-Tick, but does not corrupt the size of the figure using tight_layout().
Here is a minimal example:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0,1,num=11)
y = np.linspace(1,.42,num=11)
fig,axs = plt.subplots(1,1)
axs.plot(x,y)
locator=MaxNLocator(prune='both',nbins=5)
axs.yaxis.set_major_locator(locator)
plt.tight_layout()
fig.show()
Here is a link to a example-pdf, which shows the problems with height of upper boxline.
I tried to work with adjust_subplots() but this is of no use for me, because I vary the size of the figures and want to have same the font size all the time, which changes the margins.
Question is:
How can I use MaxNLocator and specify a number which has to be in the y-axis?
Hopefully someone of you has some advice.
Greetings,
Laenan
Assuming that you know in advance how many plots there will be in 1 row on a page one way to solve this would be to put all those plots into one figure - matplotlib will make sure they are alinged on axes:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
x = np.linspace(0, 1, num=11)
y = np.linspace(1, .42, num=11)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(8,3), gridspec_kw={'wspace':.2})
ax1.plot(x,y)
ax2.plot(x,y)
locator=MaxNLocator(prune='both', nbins=5)
ax1.yaxis.set_major_locator(locator)
# You don't need to use tight_layout and using it might give an error
# plt.tight_layout()
fig.show()

Curious Matplotlib tick label alignment

This code:
import numpy as np
import matplotlib.pyplot as plt
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
x = range(26)
v = np.random.random(26)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(x, v, width=0.8, align='center')
ax.set_xticks(x)
ax.set_xticklabels(letters)
plt.savefig('so.eps')
Generates the figure below:
As you can see, the 'Q' is not aligned with the baseline properly and looks wrong.
Can anyone shed any light on this? If it's a bug in Matplotlib, is there a hack to get round it (e.g. by realigning a single xtick label)?
I have text.usetex : True in my matplotlibrc file, and the problem only seems to show when I save the figure as eps.

Categories

Resources