I'm using pandas to import 256x256 numbers of data which I want to plot using (something similar to) sns.heatmap().
I read the data into a pandas dataframe like this:
df_Data = pd.read_csv(datapath,sep="\t",header=None)
As a trial run to see clearly what's happening my data looks like this (it doesn't have any labels as it's extracted directly from other software with just the raw numbers):
100 100 100 100 100 100 100 100 0 0 0 0 0 ..... 0
100 100 100 100 100 100 100 100 0 0 0 0 0 ..... 0
100 100 100 100 100 100 100 100 0 0 0 0 0 ..... 0
100 100 100 100 100 100 100 100 0 0 0 0 0 ..... 0
100 100 100 100 100 100 100 100 0 0 0 0 0 ..... 0
0 . ... ... ... ... ... ... ... ... ... ... ... 0
... ... ... ... ... ... ... ... ... ... ... ... .
0 . ... ... ... ... ... ... ... ... ... ... ... 0
I would like to rotate it by 270 degrees so that the highlighted part is in the bottom left corner, so that it looks like this (ideally with more sensible axis label formatting instead of what I did in ppt, but that's a detail):
I plot it with seaborn like this:
sns.heatmap(df_IntegratedData)
What's the most convenient way of doing this?
CodePudding user response:
You can rotate the array in the dataframe using
df1 = pd.DataFrame(np.rot90(df), index=reversed(df.columns), columns=df.index)
sns.heatmap(df1)
CodePudding user response:
Ideally this should be a transformation of the visualization instead of the underlying data, which is an inversion of your y-axis. However, since matplotlib
does not implement a swap_axes
type of API, you'll need to transpose your data.
To rotate a heatmap using pandas & matplotlib methods, you can draw a heatmap of the transposed dataframe, and then invert your y-axis:
Transpose & Invert the y-axis
import seaborn as sns
import numpy as np
import pandas as pd
data = np.zeros((10,15))
data[0,0] = 1
df = pd.DataFrame(data)
ax = sns.heatmap(df.T)
ax.invert_yaxis()
Side-by-side example
import seaborn as sns
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data = np.zeros((10,15))
data[0,0] = 1
df = pd.DataFrame(data)
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(16, 4))
sns.heatmap(df, ax=ax1)
ax1.set_title('no changes')
sns.heatmap(df.T, ax=ax2)
ax2.set_title('transposed')
sns.heatmap(df.T, ax=ax3)
ax3.invert_yaxis()
ax3.set_title('transposed w/ inverted y-axis')