Home > Blockchain >  Bar with different color
Bar with different color

Time:07-12

I am working with matplotlib and below you can see my data and my plot.

data = {
         'type_sale': ['g_1','g_2','g_3','g_4','g_5','g_6','g_7','g_8','g_9','g_10'],
         'open':[70,20,24,150,80,90,60,90,20,20],
        }

df = pd.DataFrame(data, columns = ['type_sale',
                                   'open',
                                   ])

df.plot(x='type_sale', kind='bar', title='Bar Graph')

enter image description here

So now I want to put a different color (color = 'red') on the fourth bar. I tryed but I colored all instead only one. So can anybody help me how to solve this ?

CodePudding user response:

The ax.bar() method returns a list of bars that you can then manipulate, in your case with .set_color():

import matplotlib.pyplot as plt
 
f=plt.figure()
ax=f.add_subplot(1,1,1)

## bar() will return a list of bars
barlist = ax.bar([1,2,3,4], [1,2,3,4])
barlist[3].set_color('r')

plt.show()

CodePudding user response:

You can try this solution

# libraries
import numpy as np
import matplotlib.pyplot as plt
 
# create a dataset
height = [3, 12, 5, 18, 45]
bars = ('A', 'B', 'C', 'D', 'E')
x_pos = np.arange(len(bars))

# Create bars with different colors
plt.bar(x_pos, height, color=['black', 'red', 'green', 'blue', 'cyan'])

# Create names on the x-axis
plt.xticks(x_pos, bars)

# Show graph
plt.show()

Here is the documentation link Link

  • Related