matplotlib 如何在pyplot图上使用千位分隔符

guicsvcw  于 2023-03-13  发布在  其他
关注(0)|答案(1)|浏览(213)

我正在绘制图表,但是y轴上的值达到了175000。当然,python和pyplot默认不使用千位分隔符。图表必须按照格式规则放入文章中。因此我使用 rc 库来拥有一个serif字体,并且允许使用latex。2但是规则也要求一个千位分隔符。我正在从数据框中绘制图表,并找到了答案,我可以在整个数据框中包含逗号千位分隔符。然后我可以使用.replace()将逗号替换为空格。但问题是,当我的 Dataframe 中有千位分隔符时,我的图表不会显示。内核只是继续运行,没有任何图表作为输出。
所以我的问题是,有没有办法引入空格千位分隔符,然后用Pyplot将其绘制出来?最好是这样的一行或两行代码,我可以将其应用于整个 Dataframe ,而不是必须一次应用于一列,但任何解决方案都将受到赞赏。
附件是我的代码。

  1. import numpy as np
  2. import pandas as pd
  3. from matplotlib import pyplot as pp
  4. %matplotlib inline
  5. from matplotlib import rc
  6. rc("text", usetex=True)
  7. rc("font", family="serif")
  8. sketsverhouding = 4 / 5
  9. vol = 5, 5*sketsverhouding
  10. half = 3, 3*sketsverhouding
  11. derde = 2.3, 2.3*sketsverhouding

下面是用于获取整个数据框中逗号分隔符的代码,它不能用图形表示。

  1. data = pd.read_excel(r"C:\Users\pivde\Desktop\Tuks\nagraads\karakterisering\xrd\sifeksp_filament.xlsx", sheet_name = "python_data")
  2. data = data.applymap(lambda x: f'{x:,d}' if isinstance(x, int) else x)

但是如果我用这个代替

  1. data = pd.read_excel(r"C:\Users\pivde\Desktop\Tuks\nagraads\karakterisering\xrd\sifeksp_filament.xlsx", sheet_name = "python_data")

我可以正常地绘制图表,但是它们没有千位分隔符。我的绘图函数如下所示,其中有两行数据。

  1. def skets(y, etiket):
  2. pp.figure(figsize=half)
  3. pp.plot(data['2theta'], data[y], 'k-')
  4. pp.xlabel(r'2$\theta$ [$^\circ$]')
  5. pp.ylabel('Intensity')
  6. pp.tight_layout()
  7. pp.ylim(0, 15000)
  8. pp.savefig(naam.format(etiket))
  9. naam = 'grafieke/xrd_sifekpsfil_{:03.0f}ldh_pla.svg'
  10. skets('n', 0)
  11. skets('t', 2)

我不能附上excel文件与数据,所以我附上了一个简化的数据集,为您提供方便,有足够的数据来说明这一点。

  1. 2theta = [4.998436247,10.63245752,20.27627772,30.37691046,40.62981404,50.83196067,61.08486426,70.01808718]
  2. n = [6090,1387,6762,3178,2865,2121,1354,1243]
  3. t = [6146,2266,8610,4012,3424,2390,1572,1355]
k5hmc34c

k5hmc34c1#

一种方法是使用format()函数添加,,然后使用replace将其更改为空格。我已经在下面的代码中完成了这一操作,它将独立运行。希望这是您正在寻找的...

  1. theta = [4.998436247,10.63245752,20.27627772,30.37691046,40.62981404,50.83196067,61.08486426,70.01808718]
  2. n = [6090,1387,6762,3178,2865,2121,1354,1243]
  3. t = [6146,2266,8610,4012,3424,2390,1572,1355]
  4. import numpy as np
  5. import pandas as pd
  6. from matplotlib import pyplot as pp
  7. %matplotlib inline
  8. import matplotlib as mpl
  9. mpl.rcParams.update(mpl.rcParamsDefault)
  10. from matplotlib import rc
  11. #rc("text", usetex=True)
  12. rc("font", family="serif")
  13. sketsverhouding = 4 / 5
  14. vol = 5, 5*sketsverhouding
  15. half = 3, 3*sketsverhouding
  16. derde = 2.3, 2.3*sketsverhouding
  17. def skets(y, etiket):
  18. pp.figure(figsize=half)
  19. pp.plot(theta, n, 'k-')
  20. pp.xlabel(r'2$\theta$ [$^\circ$]')
  21. pp.ylabel('Intensity')
  22. pp.ylim(0, 15000)
  23. labels = pp.gca().get_yticks()
  24. pp.gca().get_yaxis().set_major_formatter(mpl.ticker.FuncFormatter(lambda x, p: '{:,}'.format(x).replace(',', ' ')))
  25. skets('n', 0)

输出图

展开查看全部

相关问题