I have seaborn heatmap and I would like to plot a lineplot on top of it while using the same x and y axis that the heatmap is using.
I expected the line to behave like in this post and take up most of the space of the heatmap, but instead the output I got was the following plot where it only occupied a small section of the heatmap. How can I make the line take up most of the space in the heatmap?
Below is the minimal working example that produced the plot I linked above.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
num = 11
a = np.eye(num)
x = np.round(np.linspace(0, 1, num=num), 1)
y = np.round(np.linspace(0, 1, num=num), 1)
df = pd.DataFrame(a, columns=x, index=y)
f, ax = plt.subplots()
ax = sns.heatmap(df, cbar=False)
ax.axes.invert_yaxis()
sns.lineplot(x=x, y=y)
plt.show()
Perhaps just a simple fix here:
sns.lineplot(x=x*num, y=y*num)
Related
I want to add another plot next to pairplot result in the same figure.
For example, this code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.datasets import load_iris
iris = load_iris()
data = pd.DataFrame(data = np.c_[iris['data'], iris['target']], columns = iris['feature_names'] + ['target'])
sns.pairplot(data)
plt.show()
plt.plot(data['sepal length (cm)'].to_numpy())
plt.show()
I want to somehow have both the pairplot and the lineplot (plt.plot(data['sepal length (cm)'].to_numpy())) to be on the same figure.
Is there a way to do so?
Like getting the figure of pairplot, extend it or something?
Update
I am not after adding a plot onto one of the pairplot axis. I want to add additional axis in the figure.
Mentally, think like:
f, ax = plt.subplots(1, 2)
ax[0] = pairplot...
ax[1] = something else...
But since pairplot returns a figure element can we add to it an axis? Change its size to be able to add more axis?
I have used FacetGrid() from the seaborn module to break a line graph into segments with labels for each region as the title of each subplot. I saw the option in the documentation to have the x-axes be independent. However, I could not find anything related to having the plot sizes correspond to the size of each axis.
The code I used to generate this plot, along with the plot, are found below.
import matplotlib.pyplot as plt
import seaborn as sns
# Added during Edit 1.
sns.set()
graph = sns.FacetGrid(rmsf_crys, col = "Subunit", sharex = False)
graph.map(plt.plot, "Seq", "RMSF")
graph.set_titles(col_template = '{col_name}')
plt.show()
Plot resulting from the above code
Edit 1
Updated plot code using relplot() instead of calling FacetGrid() directly. The final result is the same graph.
import matplotlib.pyplot as plt
import seaborn as sns
# Forgot to include this in the original code snippet.
sns.set()
graph = sns.relplot(data = rmsf_crys, x = "Seq", y = "RMSF",
col = "Subunit", kind = "line",
facet_kws = dict(sharex=False))
graph.set_titles(col_template = '{col_name}')
plt.show()
Full support for this would need to live at the matplotlib layer, and I don't believe it's currently possible to have independent axes but shared transforms. (Someone with deeper knowledge of the matplotlib scale internals may prove me wrong).
But you can get pretty close by calculating the x range you'll need ahead of time and using that to parameterize the gridspec for the facets:
import numpy as np, seaborn as sns
tips = sns.load_dataset("tips")
xranges = tips.groupby("size")["total_bill"].agg(np.ptp)
xranges *= 1.1 # Account for default margins
sns.relplot(
data=tips, kind="line",
x="total_bill", y="tip",
col="size", col_order=xranges.index,
height=3, aspect=.65,
facet_kws=dict(sharex=False, gridspec_kws=dict(width_ratios=xranges))
)
I am trying to make a line plot using seaborn and in the image link I have attached
it seems like it did not show the required dates (daily) in the x-axis. How can I fix this chart?
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.style.use(['ggplot'])
import seaborn as sns
sns.set_style("whitegrid")
fig, g = plt.subplots(figsize = (20,6))
g = sns.lineplot(x="photosim_date", y="tdpower_mean", hue="tool_id", style="tool_id", data=df1, dashes=False, ax=g)
plt.ylim(80,140)
plt.title("L8 PhotoSIM SDET TDP Data")
plt.show(g)
You can change the x-axis tick locator.
loc = matplotlib.dates.DayLocator(bymonthday=range(1,32))
ax.xaxis.set_major_locator(loc)
Be wary that the axis labels will most likely overlap in this case. You can use fig.autofmt_xdate() to automatically rotate the labels.
I've a continuous stream of data which is basically bins of a histogram.
I can plot a in real-time if use something like following:
import pylab as plt
from matplotlib.pyplot import figure, show
import numpy as np
plt.ion()
X = np.linspace(0,4095,16)
Y = np.linspace(0,10000,16)
f, axarr = plt.subplots(4, sharex=True)
graph_low, = axarr[0].plot(X,Y,label='SomeLabel')
graph_low.set_ydata(Z)
But this only plots a line-plot.
The issue is I can't find something similar to set_ydata for a bar plot.
Does this do the job for you?
ax = plt.bar(left, height)
ax.patches[i].set_height(x)
where i is the index for a particular bar and x is the desired height.
I want to increase the tick label size corresponding to the colorbar in a heatmap plot created using the seaborn module. As an example:
import seaborn as sns
import pandas as pd
import numpy as np
arr = np.random.random((3,3))
df = pd.DataFrame(arr)
ax = sns.heatmap(arr)
Usually I would change the labelsize keyword using the tick_params method on a colorbar axes object, but with the heatmap() function I can only pass kwargs to the colorbar constructor. How can I modify the tick label size for the colorbar in this plot?
Once you call heatmap the colorbar axes will get a reference at the axes attribute of the figure object. So you could either set up the figure ahead of time or get a reference to it after plotting with ax.figure and then pull the colorbar axes object out that way:
import seaborn as sns
import pandas as pd
import numpy as np
arr = np.random.random((3,3))
df = pd.DataFrame(arr)
ax = sns.heatmap(arr)
cax = ax.figure.axes[-1]
cax.tick_params(labelsize=20)
A slightly different way that avoids gcf():
import seaborn as sns
import pandas as pd
import numpy as np
arr = np.random.random((3,3))
df = pd.DataFrame(arr)
fig, ax = plt.subplots()
sns.heatmap(arr, ax=ax)
ax.tick_params(labelsize=20)
I almost always start my plots this way, by explicitly creating a fig and ax object. It's a bit more verbose, but since I tend to forget my matplotlib-foo, I don't get confused with what I'm doing.