Reputation: 97
I need some help plotting my data. Is there a way to plot a bar graph with different colors. For example I would like to have a legend showing a green dot with the text positive and red dot with the text negative. Furthermore, if the graph value falls below 0 add a red color. If it is above 0 add a green color? Is this possible? Any help in the right direction would be greatly appreciated.
Is it possible?
See my code below:
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
df = pd.DataFrame({'Years': ['2015', '2016', '2017', '2018'],
'Value': [-495982.0, 405549.0, -351541.0, 283790.0]})
values = df["Value"]
values = values / 1e3
asOfDates = df['Years']
Value = df['Value']/100
fig, ax = plt.subplots()
ax.set_title('Plotting Financials')
ax.set_xlabel('Years')
ax.set_ylabel('value')
plt.bar(asOfDates,values)
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
plt.show()
Upvotes: 0
Views: 2177
Reputation: 80574
plt.bar
accepts a parameter color=
which either can be a single color, or a list with one color for each of the bars. The list can be constructed via list comprehension, giving a color depending on a constraint.
A bar plot normally only generates one entry in the legend (via plt.bar(..., label='my barplot')
. To get more than one label, and also to have it circular instead of rectangular, custom legend elements can be created.
Here is some example code to get you started:
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib
df = pd.DataFrame({'Years': ['2015', '2016', '2017', '2018'],
'Value': [-495982.0, 405549.0, -351541.0, 283790.0]})
values = df["Value"]
values = values / 1e3
asOfDates = df['Years']
Value = df['Value'] / 100
fig, ax = plt.subplots()
ax.set_title('Plotting Financials')
ax.set_xlabel('Years')
ax.set_ylabel('value')
plt.bar(asOfDates, values, color=['r' if v < 0 else 'g' for v in values])
ax.get_yaxis().set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, p: format(int(x), ',')))
legend_handles = [Line2D([0], [0], linewidth=0, marker='o', markerfacecolor=color, markersize=12, markeredgecolor='none')
for color in ['g', 'r']]
ax.legend(legend_handles, ['positive', 'negative'])
plt.show()
Upvotes: 2