How to remove x and y axis labels in a clustermap? - python

I am creating a plot based on a DataFrame:
cg = sns.clustermap(df_correlations.T)
The problem is that the x and y axis have unwanted labels in it which come from a hierarchical index. Thus I want to try and remove those labels e.g. like this:
ax = cg.fig.gca()
ax.set_xlabel('')
ax.set_ylabel('')
But this has no effect. How can I remove the labels on the x and y axis?

Without a mcve of the issue it's hard to know where the labels come from (I don't know how the dataframe needs to look like such that labels are produced, because by default there should not be any labels.) However, the labels can be set - and therefore also set to an empty string - using the known methods .set_xlabel and .set_ylabel of the heatmap axes of the cluster grid.
So if g is a ClusterGrid instance,
g = sns.clustermap(...)
you can get the heatmap axes via
ax = g.ax_heatmap
and then use any method you like to manipulate this matplotlib axes.
ax.set_xlabel("My Label")
ax.set_ylabel("")

Turn off xticklabel, and yticklabel will address your problem.
sns.clustermap(df,yticklabels=False,xticklabels=False)

try plt.axis('off'), it may solve your problem.

Related

How to switch direction of axis in 3D scatterplot plotly?

I plotted the following using plotly and got the resulting plot shown before. X is the # of hours in a day, Y is a proportion between 0-1, and Z is a categorical variable with levels {0,1,2}.
However, it's unclear why the X seems to be going the opposite direction of what we're used to with a 3D Cartesian place where it's down(-) and up(+), left(-) and right(+), and front(-) and back(+). However, X seems to decrease from front to back instead of increase. I am new to plotly and am not sure how to flip the axis so it goes from 0 to 1 instead of 1 to 0. I would greatly appreciate help on this!
fig = px.scatter_3d(X_combined, x='x', y='y', z='z',
color='set', symbol='predictions', opacity=0.7)
fig.update_traces(marker=dict(size=12,
line=dict(width=5,
color='Black')),
selector=dict(mode='markers'))
For 3D plots, the options for axes are under layout.scene.
The autorange option is therefore located under layout.scene.xaxis.autorange and can be modified like this:
fig.update_scenes(xaxis_autorange="reversed")
References:
python/3d-axes
python/layout-scene-xaxis-autorange
This should do the trick:
fig.update_xaxes(autorange="reversed")
Alternatively, you can reverse it with a specific range:
fig.update_xaxes(range=[9, 3])

Python, Seaborn: Logarithmic Swarmplot has unexpected gaps in the swarm

Let's look at a swarmplot, made with Python 3.5 and Seaborn on some data (which is stored in a pandas dataframe df with column lables stored in another class. This does not matter for now, just look at the plot):
ax = sns.swarmplot(x=self.dte.label_temperature, y=self.dte.label_current, hue=self.dte.label_voltage, data = df)
Now the data is more readable if plotted in log scale on the y-axis because it goes over some decades.
So let's change the scaling to logarithmic:
ax.set_yscale("log")
ax.set_ylim(bottom = 5*10**-10)
Well I have a problem with the gaps in the swarms. I guess they are there because they have been there when the plot is created with a linear axis in mind and the dots should not overlap there. But now they look kind of strange and there is enough space to from 4 equal looking swarms.
My question is: How can I force seaborn to recalculate the position of the dots to create better looking swarms?
mwaskom hinted to me in the comments how to solve this.
It is even stated in the swamplot doku:
Note that arranging the points properly requires an accurate transformation between data and point coordinates. This means that non-default axis limits should be set before drawing the swarm plot.
Setting an existing axis to log-scale and use this for the plot:
fig = plt.figure() # create figure
rect = 0,0,1,1 # create an rectangle for the new axis
log_ax = fig.add_axes(rect) # create a new axis (or use an existing one)
log_ax.set_yscale("log") # log first
sns.swarmplot(x=self.dte.label_temperature, y=self.dte.label_current, hue=self.dte.label_voltage, data = df, ax = log_ax)
This yields in the correct and desired plotting behaviour:

manipulate tick labels on a colorbar

I want to access the tick labels on my matplotlib colobar, so that I can manipulate them.
My starting labels may be [-2,-1,0,1,2] for example.
I have used:
locs,oldlabels = plt.xticks()
newlabels = ['a','b','c','d','e']
plt.xticks(locs, newlabels)
This works. But I don't want to manually write in the new labels. I want to access the oldlabels, so that I can have the newlabels as say [2*(-2), 2*(-1), 2*0, 2*1, 2*2].
I just don't know how to 'get at' the oldlabels. I googled everything and tried lots of things, but I'm doing something fundamentally wrong.
I tried to print oldlabels[0], but I get Text(0,0,u'\u22122.0').
EDIT:
I'm currently doing:
new_labels = [1,2,3,4,5,6,7,8,9]
colorbarname.ax.set_xticklabels(new_labels)
which works. But I want to set them as 2 x their old value. How can I do this automatically? I need to extract the old label values, multiply by (say) 2, update the axis labels with the new values.
If your data is not confined to [0,1], I'd recommend using a norm when you pass the data to the colormap instead of changing the data and relabeling the colorbar: http://matplotlib.org/api/cm_api.html?highlight=norm%20colormap#matplotlib.cm.ScalarMappable.norm
However, you can relabel the colorbar by manipulating the underlying axis directly:
import numpy as np
import pylab as plt
A = np.random.random((10,10))
plt.subplot(121)
plt.imshow(A,interpolation='nearest')
cb = plt.colorbar()
oldlabels = cb.ax.get_yticklabels()
print(map(lambda x: x.get_text(),oldlabels))
newlabels = map(lambda x: str(2 * float(x.get_text())), oldlabels)
print(newlabels)
cb.ax.set_yticklabels(newlabels)
plt.show()
oh, and now I find the matplotlib gallery example, nearly the same: http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html

Space between Y-axis and First X tick

Matplotlib newbie here.
I have the following code:
from pylab import figure, show
import numpy
fig = figure()
ax = fig.add_subplot(111)
plot_data=[1.7,1.7,1.7,1.54,1.52]
xdata = range(len(plot_data))
labels = ["2009-June","2009-Dec","2010-June","2010-Dec","2011-June"]
ax.plot(xdata,plot_data,"b-")
ax.set_xticks(range(len(labels)))
ax.set_xticklabels(labels)
ax.set_yticks([1.4,1.6,1.8])
fig.canvas.draw()
show()
When you run that code, the resulting chart has a run-in with the first tick label (2009-June) and the origin. How can I get the graph to move over to make that more readable? I tried to put dummy data in, but then Matplotlib (correctly) treats that as data.
add two limits to the x and y axes to shift the tick labels a bit.
# grow the y axis down by 0.05
ax.set_ylim(1.35, 1.8)
# expand the x axis by 0.5 at two ends
ax.set_xlim(-0.5, len(labels)-0.5)
the result is
Because tick labels are text objects you can change their alignment. However to get access to the text properties you need to go through the set_yticklabels function. So add the line:
ax.set_yticklabels([1.4,1.6,1.8],va="bottom")
after your set_yticks call. Alternatively if you go through the pylab library directly, instead of accessing the function through the axes object, you can just set that in one line:
pylab.yticks([1.4,1.6,1.8],va="bottom")
I suggest change Y axis limits:
ax.set_ylim([1.2, 1.8])

Changing axis values on a plot

How can I change the data on one axis?
I'm making some spectrum analysis on some data and my x-axis is the index of some matrix. I'd like to change it so that the x-axis becomes the data itself.
I'm using the imshow() to plot the data (I have a matrix whose elements are some intensity, the y axes are their detector-source correspondent pair and the x-axis should be their frequency).
The code for it is written down here:
def pltspec(dOD, self):
idx = 0
b = plt.psd(dOD[:,idx],Fs=self.fs,NFFT=512)
B = np.zeros((2*len(self.Chan),len(b[0])))
for idx in range(2*len(self.Chan)):
b = plt.psd(dOD[:,idx],Fs=self.fs,NFFT=512)
B[idx,:] = 20*log10(b[0])
fig = plt.figure()
ax = fig.add_subplot(111)
plt.imshow(B, origin = 'lower')
plt.colorbar()
locs, labels = xticks(find(b[1]), b[1])
plt.axis('tight')
ax.xaxis.set_major_locator(MaxNLocator(5))
I think if there's a way of interchanging the index of some array with its value, my problem would be solved.
I've managed to use the line locs, labels = xticks(find(b[1]), b[1]). But with it on my graph my axis interval just isn't right... I think it has something to do with the MaxNLocator (which I used to decrease the number of ticks).
And if I use the xlim, I can set the figure to be what I want, but the x axis is still the same (on that xlim I had to use the original data to set it right).
What am I doing wrong?
Yes, you can use the xticks method exemplified in this example.
There are also more sophisticated ways of doing it. See ticker.

Categories

Resources