Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

python - Keeping some ticks in Seaborn heatmap plot

I have this data frame:

Position    FLK
75.38   1.653608512
75.45   2.404366644
75.47   4.281285701
75.48   5.457803236
75.56   4.281285701
75.61   3.348777004
75.63   5.457803236
75.67   4.281285701
75.70   2.863168526
75.74   2.404366644
75.75   2.863168526
75.78   2.863168526
75.93   3.348777004
75.96   2.863168526
75.99   2.863168526
76.07   0.167253206
76.11   2.863168526
76.14   2.863168526

I used this script for heatmap plotting in Seaborn:

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
df = pd.read_csv("D.txt",delimiter=r"s+",header=0)
df.set_index('Position')
FLK=(df[['FLK']]).T
sns.heatmap(FLK)
plt.show()

and then get this figure:

enter image description here

I want to know how can I keep some x-ticks (0,2,3,4,5,6,12,15) in this plot, like this: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use plt.ticks to select certain tick positions. The way this heatmap is created, generates x ticks with text labels with names '0', '1', '2', ... at positions 0.5, 1.5, 2.5, .... . Therefore, you can select some of the ticks via plt.xticks(np.array([0, 2, 3, 4, 5, 6, 12, 15]) + 0.5).

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'FLK': np.random.uniform(0, 5, 18)})
FLK = (df[['FLK']]).T
sns.heatmap(FLK)
plt.xticks(np.array([0, 2, 3, 4, 5, 6, 12, 15]) + 0.5)
plt.tight_layout()
plt.show()

example plot

PS: Note that df.set_index('Position') either needs to be assigned again to df or needs the parameter inplace=True to have some effect. In that case, the labels would be these indices, for which you can select a subset with the same plt.xticks(np.array([0, 2, 3, 4, 5, 6, 12, 15]) + 0.5).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...