1
$\begingroup$

I am using the below script to get the histogram plot for all values together. However, I want a single plot but different colours for different groups (A, B, C)

data file

Group_name  code-1    code-2    Expression
GroupA  6  6  1.21
GroupA  6  8  0.611
GroupA  6  1  0.448
GroupA  6  3  0.3587
GroupB  8  6  0.611
GroupB  8  8  2.11
GroupB  8  1  0.60113
GroupB  8  3  0.534858
GroupC  1  6  0.448
GroupC  1  8  0.60113
GroupC  1  1  2.2
GroupC  1  3  0.622206

Script

import matplotlib.pyplot as plt
import seaborn as sns
plt.rcParams["figure.figsize"] = (12,8)

g1 = sns.histplot(df.Expression)
g1.set(
    xlim=(-2,2),
    title="Expression"
)
g1.axvline(0.0, c='black', linestyle="--")
g1.axvline(df.Expression.median(), c='red', linestyle="--")

```
$\endgroup$
0

1 Answer 1

1
$\begingroup$

Just change your g1 = sns.histplot(df.Expression) to g1 = sns.histplot(data=df, x="Expression", hue="Group_name")

Here's the full code:

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

plt.rcParams["figure.figsize"] = (12,8)

df = pd.DataFrame({
    "Group_name": ["GroupA", "GroupA", "GroupA", "GroupA", "GroupB", "GroupB", "GroupB", "GroupB", "GroupC", "GroupC", "GroupC", "GroupC"],
    "code-1": [6, 6, 6, 6, 8, 8, 8, 8, 1, 1, 1, 1],
    "code-2": [6, 8, 1, 3, 6, 8, 1, 3, 6, 8, 1, 3],
    "Expression": [1.21, 0.611, 0.448, 0.3587, 0.611, 2.11, 0.60113, 0.534858, 0.448, 0.60113, 2.2, 0.622206]
})
 
g1 = sns.histplot(data=df, x="Expression", hue="Group_name")
g1.set(
    xlim=(-2,2),
    title="Expression"
)
g1.axvline(0.0, c='black', linestyle="--")
g1.axvline(df.Expression.median(), c='red', linestyle="--")

g1.figure.savefig("hist.png")

'''New output

$\endgroup$
1
  • 1
    $\begingroup$ Thanks, very impressive Seaborn coding $\endgroup$
    – M__
    Commented Jan 22, 2023 at 18:34

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.