matplotlib 多标签条形图

k7fdbhmy  于 2023-10-24  发布在  其他
关注(0)|答案(3)|浏览(127)

下面的代码只显示主类别[“one”,“two',”three',“four',”five',“six']作为x轴标签。有没有办法显示子类别[”A“,”B',“C',”D']作为辅助x轴标签?

  1. df = pd.DataFrame(np.random.rand(6, 4),
  2. index=['one', 'two', 'three', 'four', 'five', 'six'],
  3. columns=pd.Index(['A', 'B', 'C', 'D'],
  4. name='Genus')).round(2)
  5. df.plot(kind='bar',figsize=(10,4))
t1qtbnec

t1qtbnec1#

这里有一个解决方案。你可以得到这些条的位置,并相应地设置一些小的xticklabel。

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. import pandas as pd
  4. df = pd.DataFrame(np.random.rand(6, 4),
  5. index=['one', 'two', 'three', 'four', 'five', 'six'],
  6. columns=pd.Index(['A', 'B', 'C', 'D'],
  7. name='Genus')).round(2)
  8. df.plot(kind='bar',figsize=(10,4))
  9. ax = plt.gca()
  10. pos = []
  11. for bar in ax.patches:
  12. pos.append(bar.get_x()+bar.get_width()/2.)
  13. ax.set_xticks(pos,minor=True)
  14. lab = []
  15. for i in range(len(pos)):
  16. l = df.columns.values[i//len(df.index.values)]
  17. lab.append(l)
  18. ax.set_xticklabels(lab,minor=True)
  19. ax.tick_params(axis='x', which='major', pad=15, size=0)
  20. plt.setp(ax.get_xticklabels(), rotation=0)
  21. plt.show()

展开查看全部
cvxl0en2

cvxl0en22#

这里有一个可能的解决方案(我有相当多的乐趣!):

  1. df = pd.DataFrame(np.random.rand(6, 4),
  2. index=['one', 'two', 'three', 'four', 'five', 'six'],
  3. columns=pd.Index(['A', 'B', 'C', 'D'],
  4. name='Genus')).round(2)
  5. ax = df.plot(kind='bar',figsize=(10,4), rot = 0)
  6. # "Activate" minor ticks
  7. ax.minorticks_on()
  8. # Get location of the center of each rectangle
  9. rects_locs = map(lambda x: x.get_x() +x.get_width()/2., ax.patches)
  10. # Set minor ticks there
  11. ax.set_xticks(rects_locs, minor = True)
  12. # Labels for the rectangles
  13. new_ticks = reduce(lambda x, y: x + y, map(lambda x: [x] * df.shape[0], df.columns.tolist()))
  14. # Set the labels
  15. from matplotlib import ticker
  16. ax.xaxis.set_minor_formatter(ticker.FixedFormatter(new_ticks)) #add the custom ticks
  17. # Move the category label further from x-axis
  18. ax.tick_params(axis='x', which='major', pad=15)
  19. # Remove minor ticks where not necessary
  20. ax.tick_params(axis='x',which='both', top='off')
  21. ax.tick_params(axis='y',which='both', left='off', right = 'off')

我得到的是

展开查看全部
y53ybaqx

y53ybaqx3#

  1. import pandas as pd
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. def subcategorybar(X, vals,als, width=0.8):
  5. n = len(vals)
  6. _X = np.arange(len(X))
  7. plt.figure(figsize=(14,9))
  8. for i in range(n):
  9. plt.bar(_X - width/2. + i/float(n)*width, vals[i],
  10. width=width/float(n), align="edge")
  11. for j in _X:
  12. plt.text([_X - width/2. + i/float(n)*width][0][j],vals[i][j]+0.01*vals[i]
  13. [j],str(als[i][j]))
  14. plt.xticks(_X, X)
  15. ### data
  16. X = ['a','b','c','d','f']
  17. A1 = [1,2,3,4,5]
  18. A2= [1,7,6,7,8]
  19. A3 = [3,5,6,8,9]
  20. A4= [4,5,6,7,3]
  21. A5 = [5,6,7,8,5]
  22. ##labels
  23. A1_al = ['da','dd',5,6,3]
  24. A2_al = np.random.random_integers(20,size=5)
  25. A3_al = np.random.random_integers(20,size=5)
  26. A4_al = np.random.random_integers(20,size=5)
  27. A5_al = np.random.random_integers(20,size=5)
  28. subcategorybar(X, [A1,A2,A3,A4],[A1_al,A2_al,A3_al,A4_al],width=0.8)
  29. plt.show()
展开查看全部

相关问题