python - 使用 matplotlib.pyplot 指定 x 轴的值?

标签 python matplotlib

我无法使用 matplotlib.pyplot 指定 x 轴的值。

在某些图像中,chart.xticks(years)解决了问题,但似乎当x轴值集太小时,它使用默认值,如​​[ 0,1,2,...,N]。

一个有效的案例: Image

一个不起作用的案例: Image

我的代码:

import matplotlib.pyplot as chart
from matplotlib import lines

   # Settings
    chart.title(file_name)
    chart.xlabel('Years')
    chart.ylabel('Committers/Contributions')
    chart.ylim([0,highest_value + 100])
    chart.xlim(first_year,2017)

    # Values
    committer_line = chart.plot(committers_dict.keys(),committers_dict.values(),'r',label='Committer')
    contribution_line = chart.plot(contributions_dict.keys(),contributions_dict.values(),'b--',label='Contribution')
    years = list(range(first_year,2017))
    chart.xticks(years)

    # Legend
    chart.legend()

    # Show/Save
    chart.savefig(images_path + file_name.replace('.txt','-commiter-contribution.eps'), format='eps')
    chart.show()

最佳答案

Matplotlib 正在输入正确的数字,但采用科学计数法,因为 x 轴上没有更多空间可以放置更多内容。也就是说,您可以直接与 x 轴交互,并使用旋转值来说明您想要什么字符串、在什么位置。以下示例(数据是随机的):

import matplotlib.pyplot as chart
from matplotlib import lines
import random

title = 'Title'
first_year = 1960
last_year = 2017
x = [year for year in range(first_year,2017)]
y1 = [random.randint(0,10) for year in range(first_year,2017)]
y2 = [random.randint(0,10) for year in range(first_year,2017)]
highest_value = max(y1+y2)

# Settings
chart.title(title)
chart.xlabel('Years')
chart.ylabel('Committers/Contributions')
chart.ylim([0,highest_value + 0.05*highest_value])
chart.xlim(first_year,last_year)

# Values
committer_line = chart.plot(x,y1,'r',label='Committer')
contribution_line = chart.plot(x,y2,'b--',label='Contribution')
years = list(range(first_year,last_year))
years_str = [str(i) for i in range(first_year,last_year)]
chart.xticks(years,years_str,rotation=45)

# Legend
chart.legend()

# Show/Save
#chart.savefig(images_path + file_name.replace('.txt','-commiter-contribution.eps'), format='eps')
chart.show()

,结果为:

lots of dates in x axis

,这有点困惑,所以给你一个“标签代码”范围的步骤:

years = list(range(first_year,last_year,5)) # It's 5!
years_str = [str(i) for i in range(first_year,last_year,5)] # It's 5!

,将缓和x轴信息:

a few dates on the x axis

关于python - 使用 matplotlib.pyplot 指定 x 轴的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36184953/

相关文章:

python - 在启动时运行 Python 脚本(Raspberry Pi 上的 Arch Linux ARM)

Python 属性错误 : 'numpy.ndarray'

python - 如何找出当前系统首选语言是什么

python - argmax 用于沿某个轴的多维数组

python - 几分钟后 numpy plot 创建图形失败 idel

matplotlib - 在 matplotlib 中用圆裁剪三角形

python - subplot2grid 与 seaborn 覆盖相同的斧头

python - 按下 "Enter"后 PyQt QItemDelegate setFocus 到 QTableWidget

python - 结合 seaborn 在 matplotlib 中自动选择线条样式的最可靠方法

python - matplotlib 只能更新最新的点到图中吗?