How to show different colors on a plot for values from different columns
Question:
Please consider the small dataframe test:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
[
[1, 1.0, 0.0, 0.0],
[1, 0.75, 0.25, 0.0],
[1, 0.576, 0.396, 0.028]
],
columns = ["State", "1", "2", "3"]
)
I am now plotting the 3 last columns by:
fig = plt.figure()
ax = plt.subplot()
ax.plot(df[["1","2","3"]], label = ["1 (from 1)","2 (from 1)","3 (from 1)"],
color = "red", marker = ".", linestyle="-")
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),
fancybox=True, shadow=True)
plt.show()
What would be the easiest way to show a different color for each column of data, such as "red" for column 1, "blue" for column 2 and green for column 3 ?
Answers:
I would say that the easiest way would be to use the pandas built-in plot
.
Otherwise, you need to loop :
fig, ax = plt.subplots()
colors = ["red", "blue", "green"]
labels = ["1 (from 1)","2 (from 1)","3 (from 1)"]
for idx, col in enumerate(["1", "2", "3"]):
ax.plot(df[col], label=labels[idx], color=colors[idx], marker=".", linestyle="-")
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5),
fancybox=True, shadow=True)
plt.show();
Output :
You can also use .plot.line():
df1 = df[["1","2","3"]]
axes = df1.plot.line(subplots=False, color={"1": "red", "2": "blue", "3":"green"})
or .plot(style={})
axes = df1.plot(style={"1": "*:r", "2": "-.b", "3":"+--g"})
Please consider the small dataframe test:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(
[
[1, 1.0, 0.0, 0.0],
[1, 0.75, 0.25, 0.0],
[1, 0.576, 0.396, 0.028]
],
columns = ["State", "1", "2", "3"]
)
I am now plotting the 3 last columns by:
fig = plt.figure()
ax = plt.subplot()
ax.plot(df[["1","2","3"]], label = ["1 (from 1)","2 (from 1)","3 (from 1)"],
color = "red", marker = ".", linestyle="-")
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5),
fancybox=True, shadow=True)
plt.show()
What would be the easiest way to show a different color for each column of data, such as "red" for column 1, "blue" for column 2 and green for column 3 ?
I would say that the easiest way would be to use the pandas built-in plot
.
Otherwise, you need to loop :
fig, ax = plt.subplots()
colors = ["red", "blue", "green"]
labels = ["1 (from 1)","2 (from 1)","3 (from 1)"]
for idx, col in enumerate(["1", "2", "3"]):
ax.plot(df[col], label=labels[idx], color=colors[idx], marker=".", linestyle="-")
ax.legend(loc="center left", bbox_to_anchor=(1, 0.5),
fancybox=True, shadow=True)
plt.show();
Output :
You can also use .plot.line():
df1 = df[["1","2","3"]]
axes = df1.plot.line(subplots=False, color={"1": "red", "2": "blue", "3":"green"})
or .plot(style={})
axes = df1.plot(style={"1": "*:r", "2": "-.b", "3":"+--g"})