Chris Turnbull
Chris Turnbull

Reputation: 87

Matplotlib and Pandas change colors of negative values

I would like to set the color of the negative values of my bar graph to 'deepskyblue' and keep the positive values 'crimson'. What is the best way to accomplish this? X-values of my csv file are latitude points and my Y-values are temperature anomalies. I also seem to be having an issue with my x-axis, as seen in my linked figure. It is plotting ticks for every latitude point from -90 to 90, which results in a lot of overlapping. I would like to have those in increments of 15, but I can't figure out how to do that.

EDIT: solved.

Final Version

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

filename = "2015_tAnoms.csv"

df = pd.read_csv(filename, delimiter=',',header='infer')

figure(num=None, figsize=(8, 6), dpi=300, facecolor='w', edgecolor='k')

ax = plt.gca()

ax.set_facecolor((0,0,0))
ax.set_ylim([-1,3])

ax.grid(color='lightgray', alpha=0.6, which='major', axis='y', linestyle='-')


plt.bar(df['Latitude'],df['TempAnom'],color=np.where(df['TempAnom'] < 0, 'deepskyblue', 'crimson'))
plt.margins(x=0)
ax.xaxis.set_ticks(np.arange(-90,91,15))

plt.xlabel("Latitude")
plt.ylabel("Temperature Anomaly (°C)")
plt.title("2015 Temperature Anomalies by Latitude Band")

Upvotes: 2

Views: 2523

Answers (1)

perl
perl

Reputation: 9941

You can pass color as series with different colors depending on df['TempAnom'] < 0 condition:

plt.bar(
    df['Latitude'], df['TempAnom'],
    color=np.where(df['TempAnom'] < 0, 'deepskyblue', 'crimson'),
)

ax.xaxis.set_ticks(np.arange(-90, 91, 15))

Output:

chart

Upvotes: 2

Related Questions