Matplotlib value based color chart

Is there a way to color stripes of velvet based on the value of the bar. For instance:

- values below -0.5: red
- values between -0.5 to 0: green
- values between 0 to 08: blue
- etc

I found some basic examples of coloring strokes, but nothing that can suit ranges of values, such as the examples above.

UPDATE:

Thank kikocorreoso for your suggestion. This works great when both axes are numbers according to your example. However, in my case, the original data structure is a pandas dataframe. Then I use df.stack () and build the result. This means that the rows / columns of the dataframes become the x axis of the graph, and the dataframe cells become the Y axis (columns).

I tried masking according to your example, but it doesn't seem to work when the Y axis is numbers and the X axis are names. eg:

     col1    col2   col3   col4
 row1 1       2      3      4
 row2 5       6      7      8
 row3 9       10     11     12
 row4 13      14     15     16

- /, . . , , .

+2
1

. :

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.arange(10) * 0.1

mask1 = y < 0.5
mask2 = y >= 0.5

plt.bar(x[mask1], y[mask1], color = 'red')
plt.bar(x[mask2], y[mask2], color = 'blue')
plt.show()

: enter image description here

UPDATE:

. , , () :

import pandas as pd

df = pd.DataFrame({'col1':[1,2,3], 'col2':[4,5,6]}, 
                  index = ['row1','row2','row3'])

dfstacked = df.stack()

mask = dfstacked <= 3

colors = np.array(['b']*len(dfstacked))
colors[mask.values] = 'r'

dfstacked.plot(kind = 'bar', rot = 45, color = colors)
plt.show()

OO.

:

  • .
  • , .
  • dfstacked dataframe MultiIndex, , rot, . , , plt.tight_layout() plt.show().

, .

+11

Source: https://habr.com/ru/post/1676752/


All Articles