Removing all but one tick on x-axis - python

I have a graph that I would tick to remove all ticks and their corresponding labels bar the first tick and label on the x-axis. How would I go about this?
import pylab
import numpy as np
import matplotlib.pyplot as plt
a=np.linspace(0,10,10000)
print a
def f(x):
return 1/(1-(x**2)*np.log((1/(x**2)+1)))
b=f(a)
fig, ax = plt.subplots(1)
ax.plot(b,a)
pylab.xlim(0.5, 5)
pylab.ylim(0, 1.5)
fig.show()

you can use ax.set_xticks([1]) to set just one xtick at 1,0.
Also, there's no need to import both pylab and matplotlib.pyplot. The recommended way now is to import matplotlib.pyplot and use all the Axes methods. E.g., you can use ax.set_xlim instead of pylab.xlim.
Here's your full script and output plot:
import numpy as np
import matplotlib.pyplot as plt
a=np.linspace(0,10,10000)
print a
def f(x):
return 1/(1-(x**2)*np.log((1/(x**2)+1)))
b=f(a)
fig, ax = plt.subplots(1)
ax.plot(b,a)
ax.set_xlim(0.5, 5)
ax.set_ylim(0, 1.5)
ax.set_xticks([1])
plt.show()

Related

Matplotlib imshow ticks are wrong with negative values

import matplotlib.pyplot as plt
import numpy as np
a = np.random.randn(5,5)
plt.imshow(a)
plt.xticks(range(5))
plt.yticks([i-2 for i in range(5)])
plt.show()
results in
??
Also imagine I had 500 instead of 5 ticks, how could I pass the ticks but have less be displayed (for example every 10th)?
Use the extent parameter, and no need to use xticks or yticks:
plt.imshow(a, extent=(-0.5, 4.5, -2.5, 2.5))
Output:
Use MultipleLocator for your second question:
from matplotlib.ticker import MultipleLocator
a = np.random.randn(500,500)
fig, ax = plt.subplots(figsize=(10, 10))
ax.imshow(a, extent=(-0.5, 500.5, -250.5, 250.5))
ax.xaxis.set_major_locator(MultipleLocator(25))
ax.yaxis.set_major_locator(MultipleLocator(25))
Output:

Matplotlib: Is there a way to get a colorbar axis from a parent axis?

I am doing a plot something like this:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
fig = plt.gcf()
ax = plt.gca()
ax.pcolormesh(np.random.rand(10, 10))
fig.colorbar(mpl.cm.ScalarMappable(), ax=ax)
The last line adds a colorbar and a second axis
fig.axes
>>> [<AxesSubplot:>, <AxesSubplot:label='<colorbar>'>]
My question:
Is there any relation between the two axes that can be used to get the axis of the colorbar (second in the list above) using only the axis returned by ax = plt.gca() (first returned in the list above)?
As far as I know, if you define pcolormesh and colorbar that way, no.
Anyway, you can define an ax for the pcolormesh and a cax for the colorbar beforehand. Then you can pass cax as parameter to matplotlib.pyplot.colorbar. In this way you can access to both axis ax and cax as you need.
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
grid_kws = {'width_ratios': (0.9, 0.05), 'wspace': 0.2}
fig, (ax, cax) = plt.subplots(1, 2, gridspec_kw = grid_kws, figsize = (10, 8))
ax.pcolormesh(np.random.rand(10, 10))
plt.colorbar(mpl.cm.ScalarMappable(), cax=cax)
plt.show()
In general, focusing on your code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
fig = plt.gcf()
ax = plt.gca()
ax.pcolormesh(np.random.rand(10, 10))
fig.colorbar(mpl.cm.ScalarMappable(), ax=ax)
starting from ax, you can get its figure with ax.figure. From there, you can get the list of all figure axes with ax.figure.axes. So, if you want to get colobar's axis using only pcolormesh' axis, you should use:
ax.figure.axes[1]
The parent figure, as far as I know, is the only relation between the two axes.

Matplotlib/Seaborn: how to plot a rugplot on the top edge of x-axis?

Suppose I draw a plot using the code below. How to plot the rug part on the top edge of x-axis?
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.distplot(np.random.normal(0, 0.1, 100), rug=True, hist=False)
plt.show()
The seaborn.rugplot creates a LineCollection with the length of the lines being defined in axes coordinates. Those are always the same, such that the plot does not change if you invert the axes.
You can create your own LineCollection from the data though. The advantage compared to using bars is that the linewidth is in points and therefore no lines will be lost independend of the data range.
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
import seaborn as sns
def upper_rugplot(data, height=.05, ax=None, **kwargs):
from matplotlib.collections import LineCollection
ax = ax or plt.gca()
kwargs.setdefault("linewidth", 1)
segs = np.stack((np.c_[data, data],
np.c_[np.ones_like(data), np.ones_like(data)-height]),
axis=-1)
lc = LineCollection(segs, transform=ax.get_xaxis_transform(), **kwargs)
ax.add_collection(lc)
fig, ax = plt.subplots()
data = np.random.normal(0, 0.1, 100)
sns.distplot(data, rug=False, hist=False, ax=ax)
upper_rugplot(data, ax=ax)
plt.show()
Rugs are just thin lines at the data points. Yo can think of them as thin bars. That being said, you can have a following work around: Plot distplot without rugs and then create a twin x-axis and plot a bar chart with thin bars. Following is a working answer:
import numpy as np; np.random.seed(21)
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax = plt.subplots()
data = np.random.normal(0, 0.1, 100)
sns.distplot(data, rug=False, hist=False, ax=ax)
ax1 = ax.twinx()
ax1.bar(data, height=ax.get_ylim()[1]/10, width=0.001)
ax1.set_ylim(ax.get_ylim())
ax1.invert_yaxis()
ax1.set_yticks([])
plt.show()

Python pyplot x-axis label rotation

I am trying to rotate the xaxis labels but the xticks function below has no effect and the labels overwrite each other
import matplotlib.pyplot as plt
import seaborn as sns
corrmat = X.corr()
plt.xticks(rotation=90)
plt.figure(figsize=(15,16))
ax = sns.heatmap(corrmat, vmin=0, vmax=1)
ax.xaxis.tick_top()
After using suggested code changes: I get the following but I still want to increase the size of the heatmap
setp looks to be the way to go with pyplot (inspiration from this answer). This works for me:
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np; np.random.seed(0)
data = np.random.rand(10, 12)
ax = sns.heatmap(data)
ax.xaxis.tick_top()
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.show()
Obviously I don't have your data, hence the numpy random data, but otherwise the effect is as required:

How do I change the plot size of a regplot in Seaborn?

Something similar to the fig.set_size_inches(18.5, 10.5) of matplotlib.
You can declare fig, ax pair via plt.subplots() first, then set proper size on that figure, and ask sns.regplot to plot on that ax
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# some artificial data
data = np.random.multivariate_normal([0,0], [[1,-0.5],[-0.5,1]], size=100)
# plot
sns.set_style('ticks')
fig, ax = plt.subplots()
fig.set_size_inches(18.5, 10.5)
sns.regplot(data[:,0], data[:,1], ax=ax)
sns.despine()
Or a little bit shorter:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
# some artificial data
data = np.random.multivariate_normal([0,0], [[1,-0.5],[-0.5,1]], size=100)
# plot
sns.set_style('ticks')
g = sns.regplot(data[:,0], data[:,1])
g.figure.set_size_inches(18.5, 10.5)
sns.despine()

Categories

Resources