英文:
How do I create a heat map from three lists in python?
问题
以下是您要翻译的代码部分:
import numpy as np
import matplotlib
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
initial_R=[]
initial_v=[]
E_total=[]
df = pd.read_clipboard()
df.drop_duplicates(['initial_R','initial_v'], inplace=True)
pivot = df.pivot(index='initial_R', columns='initial_v', values='E_total')
ax = sns.heatmap(pivot, annot=True)
plt.show()
print (pivot)
英文:
I have 3 arrays of data: initial_R, initial_v and E_total.
import numpy as np
import matplotlib
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
initial_R=[]
initial_v=[]
E_total=[]
I then have a piece of code that fills these three arrays. I wont post it here as its quite long, but it works.
initial_R is the x-coordinate, initial_v is the y-coordinate and E_total is the intensity value at those coordinates. I would like to plot this as a simple heatmap, with each square coloured one of two colours depending on if E_total is positive or negative.
df = pd.read_clipboard()
df.drop_duplicates(['initial_R','initial_v'], inplace=True)
pivot = df.pivot(index='initial_R', columns='initial_v', values='E_total')
ax = sns.heatmap(pivot,annot=True)
plt.show()
print (pivot)
I have seen the above code used before, but it doesn't work with my data, not sure how it works to be honest.
答案1
得分: 4
你可以使用 numpy.sign
来获取你的值的符号:
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'initial_R': [1, 2, 3, 1, 3, 1, 2],
'initial_v': [0, 0, 0, 1, 1, 2, 2],
'E_total': [-1, 2, -4, -3, 0, -1, 5]})
df.drop_duplicates(['initial_R','initial_v'], inplace=True)
pivot = df.pivot(index='initial_R', columns='initial_v', values='E_total')
sns.heatmap(np.sign(pivot), annot=True)
如果你想要合并0和正值:
sns.heatmap(pivot.ge(0).astype(int).mask(pivot.isna()), annot=True)
输出 1:
输出 2:
如果你想要自定义标签:
pivot2 = pivot.ge(0).astype(int).mask(pivot.isna())
sns.heatmap(pivot2, annot=pivot2.replace({0: 'negative', 1: 'positive'}), fmt='s')
输出:
英文:
You can use numpy.sign
to get the sign of your values:
import pandas as pd
import seaborn as sns
df = pd.DataFrame({'initial_R': [1, 2, 3, 1, 3, 1, 2],
'initial_v': [0, 0, 0, 1, 1, 2, 2],
'E_total': [-1, 2, -4, -3, 0, -1, 5]})
df.drop_duplicates(['initial_R','initial_v'], inplace=True)
pivot = df.pivot(index='initial_R', columns='initial_v', values='E_total')
sns.heatmap(np.sign(pivot), annot=True)
If you want to combine 0 and positive values:
sns.heatmap(pivot.ge(0).astype(int).mask(pivot.isna()), annot=True)
Output 1:
Output 2:
If you want custom labels:
pivot2 = pivot.ge(0).astype(int).mask(pivot.isna())
sns.heatmap(pivot2, annot=pivot2.replace({0: 'negative', 1: 'positive'}), fmt='s')
Output:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论