0
$\begingroup$

I have csv file containing some hierarchical data and I’d like to create a visualisation like this:

enter image description here

Anybody know how I can do this, preferably using matplotlib?

$\endgroup$

1 Answer 1

0
$\begingroup$
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
data = {
'Scope': ['Scope Insertion', 'Scope Positioning', 'No Action'],
'Instrument': ['Instrument Insertion', 'Instrument Positioning', 'No Action'],
'Site': ['Fluid Wash', 'Debris Wash', 'No Action'],
'Pressure': ['Inflate Pressure', 'Deflate Pressure', 'No Action']
}
df = pd.DataFrame(data)
palette = {
'Scope Insertion': '#4CAF50',
'Scope Positioning': '#AED581',
'No Action': '#EEEEEE',
'Instrument Insertion': '#1E88E5',
'Instrument Positioning': '#90CAF9',
'Fluid Wash': '#FFB74D',
'Debris Wash': '#8D6E63',
'Inflate Pressure': '#9E9E9E',
'Deflate Pressure': '#757575'
}
fig, ax = plt.subplots(figsize=(10, 2))
sns.heatmap(
df.applymap(palette.get).replace(palette),
annot=df,
fmt='',
cmap=palette,
cbar=False,
linewidths=.5,
ax=ax
)
ax.set_title('Setup')
ax.set_xlabel('Setup')
ax.set_ylabel('GT')
plt.show()
$\endgroup$
5
  • $\begingroup$ Thank you! I think I understand most of it. But could you say more about why you did the replace(palette)? $\endgroup$
    – K G
    Commented Jun 12 at 23:41
  • $\begingroup$ applymap(palette.get) already transforms each value to its corresponding color, the replace(palette) ensures to transform again where necessary. $\endgroup$ Commented Jun 13 at 5:12
  • $\begingroup$ Ah ok. That’s what was throwing me off since it seemed to be redundant. $\endgroup$
    – K G
    Commented Jun 13 at 5:16
  • $\begingroup$ Honestly, you are true. replace(palette) is essentially redundant in this context because df.applymap(palette.get) has already done the job of converting categorical values to colors. $\endgroup$ Commented Jun 13 at 5:35
  • $\begingroup$ I'm getting the following error when I run it: ValueError: could not convert string to float: '#4CAF50' $\endgroup$
    – K G
    Commented Jun 13 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.