1

I have a few lists as below-

Clusters=['Cluster1', 'Cluster2', 'Cluster3', 'Cluster4', 'Cluster5', 'Cluster6', 'Cluster7']

clusterpoints= [[0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
[0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
[3, 0, 0, 1, 0, 6, 2, 0, 0, 0],
[1, 4, 0, 1, 0, 0, 0, 1, 2, 1],
[0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
[0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
[3, 0, 0, 1, 0, 6, 2, 0, 0, 0]]

xaxispoints=[ V1, V2, V3 ,V4 ,V5 , V6, V7, V8 , V9 ,V10 ]

How can I plot a graph as shown in the example below ?

enter image description here

JohanC
  • 71,591
  • 8
  • 33
  • 66

2 Answers2

1

The code below produces an image similar to the one you're asking:

import matplotlib.pyplot as plt
import numpy as np

cluster_names = ['Cluster1', 'Cluster2', 'Cluster3', 'Cluster4', 'Cluster5', 'Cluster6', 'Cluster7']

cluster_points = [[0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
[0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
[3, 0, 0, 1, 0, 6, 2, 0, 0, 0],
[1, 4, 0, 1, 0, 0, 0, 1, 2, 1],
[0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
[0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
[3, 0, 0, 1, 0, 6, 2, 0, 0, 0]]

xaxispoints = ["V1", "V2", "V3" ,"V4" ,"V5" , "V6", "V7", "V8" , "V9" ,"V10" ]

width = 0.45 

fig, ax = plt.subplots()

cluster_point_sum = np.zeros(len(xaxispoints))

for (cluster_point, cluster_name) in zip(cluster_points, cluster_names):
  ax.bar(xaxispoints, cluster_point, width, label=cluster_name, bottom=cluster_point_sum)
  cluster_point_sum += cluster_point

ax.set_ylabel('Number of points')
ax.legend()

plt.show()

enter image description here

mtzd
  • 759
  • 4
  • 16
1

Here is an approach using pandas:

import pandas as pd
import numpy as np

Clusters = ['Cluster1', 'Cluster2', 'Cluster3', 'Cluster4', 'Cluster5', 'Cluster6', 'Cluster7']
clusterpoints = [[0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
                 [0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
                 [3, 0, 0, 1, 0, 6, 2, 0, 0, 0],
                 [1, 4, 0, 1, 0, 0, 0, 1, 2, 1],
                 [0, 2, 0, 5, 1, 0, 0, 0, 6, 0],
                 [0, 0, 5, 0, 0, 5, 1, 0, 1, 0],
                 [3, 0, 0, 1, 0, 6, 2, 0, 0, 0]]
xaxispoints = ['V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10']

df = pd.DataFrame(data=np.transpose(clusterpoints), columns=Clusters, index=xaxispoints)
df.plot.bar(stacked=True, rot=0)

pandas stacked bars

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • The code that worked for me is - df = pd.DataFrame(data=ppclusterPvehicleList, columns=clusternames, index=xaxispoints) Would get the following error otherwise- ValueError: Shape of passed values is (7, 10), indices imply (10, 7) – Nishanth Delavictoire May 03 '22 at 05:55
  • That's why my answer involves np.transpose. You didn't define ppclusterPvehicleList, but probably it is just the transpose of clusterpoints. – JohanC May 03 '22 at 06:19