简体   繁体   English

Python Matplotlib-如何在X轴上绘制一条线?

[英]Python matplotlib - How do I plot a line on the x-axis?

So I'm working on a new project where I'm using matplotlib to track my habits. 因此,我正在开发一个新项目,其中正在使用matplotlib跟踪我的习惯。 The y-axis is a list of all my habits (the bottom is "retainer" and the top is "UAS" (my club meetings)). y轴是我所有习惯的列表(底部是“固定器”,顶部是“ UAS”(我的俱乐部会议))。 The x-axis are the numbers 1 - days in month (1-31 for January 2018 for example). x轴是每月1天的数字(例如,2018年1月为1-31)。 I'm trying to lay a line behind the chart that will hide under the x-axis if no habits are completed, and will spike up equally to how many habits are completed on any specific day. 我正在尝试在图表后面划一条线,如果没有完成任何习惯,该线将隐藏在x轴下,并且将平均上升到在特定日期完成了多少个习惯。 My problem is that plotting the line at (0,x), or with correct syntax: plt.plot((0),(0)), actually plots it at what appears to be (1,1) or with my labels (1,"retainer"). 我的问题是在(0,x)处绘制线,或使用正确的语法:plt.plot((0),(0)),实际上以(1,1)或我的标签( 1,“固定器”)。 Which would give the impression that at least one habit was completed. 这会给人以至少一个习惯已经完成的印象。

In previous version of matplotlib it seems that there is no quarrel with graphing lines right up to the axis, but now an automatic "buffer" space is applied so you cant do that anymore. 在以前版本的matplotlib中,似乎没有争吵,直到轴上都画有线,但是现在应用了自动“缓冲区”空间,因此您不能再这样做了。

I dont want to change that buffer space, I just want to graph my line on the x-axis when no habits are completed so that it does not show. 我不想更改该缓冲区空间,我只想在没有习惯的情况下在x轴上画一条线,以使其不显示。

Current habits are just test data, which I mention because otherwise it would look kinda strange. 当前的习惯只是测试数据,我提到了这些数据,因为否则看起来会有些奇怪。

Here is a picture, followed by my code: 这是一张图片,后面是我的代码:

picture of plot, graph line is scale with completed habits (red), but is one element too high 情节的图片,图线是具有完整习惯的比例(红色),但是一个元素太高

and my code: 和我的代码:

import matplotlib.pyplot as plt
import calendar
import datetime
import atexit

def main():
    global trackers
    activities = ["Retainer","Steps Goal","Drink Water","6+ Hours Sleep","<=2 Sodas","Study","Leave Campus","Clean","Mike","Paint","Phone Call","Saw Friends","UAS"]
    trackers = []
    completed = []
    days_in_month = calendar.monthrange(int(str(datetime.datetime.now())[0:4]),int(str(datetime.datetime.now())[5:7]))[1]
    current_day = int(str(datetime.datetime.now())[8:11])
    file = open("trackers.txt","r")
    data = file.readlines()
    for i in range(len(data)):
        data[i] = data[i].rstrip("\n").rstrip("").rstrip(",")
        trackers.append(data[i].split(","))
        for b in range(len(trackers[-1])):
            trackers[-1][b] = int(trackers[-1][b])
    print("Trackers Loaded")

    plt.switch_backend('TkAgg')

    for i in range(days_in_month):
        completed.append(0)
        for b in range(len(trackers)):
            completed[-1] += trackers[b][i]

    plt.plot(tuple([i for i in range(days_in_month)]), tuple(completed),c = "k")

    plt.axvline(x=current_day - 1, c="#ccf3ff", linewidth = 30, zorder = -1)
    plt.grid()

    plt.title("Habit Tracker")
    plt.yticks([i for i in range(len(trackers))],tuple(activities))
    plt.xticks([i for i in range(days_in_month)],[i for i in range(1,days_in_month + 1)])
    for i in range(len(trackers)):
        for b in range(days_in_month):
            if trackers[i][b] == 1:
                plt.plot(b,i,"rs", markersize = 8)
            else:
                plt.plot(b,i,"s", color = "#d2d2d2", markersize = 8)

    mng = plt.get_current_fig_manager()
    mng.window.state('zoomed')

    plt.show()

    return

@atexit.register
def exit():
    file = open("trackers.txt","w")
    for i in range(len(trackers)):
        for b in range(len(trackers[i])):
            file.write(str(trackers[i][b]) + ",")
        file.write("\n")
    print("Trackers Saved")

if __name__ == "__main__":
    main()

If you want to run it, you'll need the accompanying file "trackers.txt" which saves all the habit data between program runs, here is a direct copy of my file. 如果要运行它,则需要附带的文件“ trackers.txt”,该文件保存程序运行之间的所有习惯数据,这是我的文件的直接副本。 Just copy and paste this to avoid read errors. 只需复制并粘贴此内容即可避免读取错误。 Make sure to add a blank line at the end of this file! 确保在该文件的末尾添加一个空行!

0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,

Thank you in advance! 先感谢您!

I think the x-axis is not where you think it is. 我认为x轴不在您认为的位置。 In this line you set the y ticks: 在此行中,设置y刻度:

plt.yticks([i for i in range(len(trackers))],tuple(activities))

range starts at 0, so your first activity label is labeling y=0. range从0开始,因此您的第一个活动标签为y = 0。 That is, the line that says "retainer" is the x-axis. 即,表示“保持器”的线 x轴。

If you want your first label to be at height 1, then you should add one to your ticks: 如果您希望第一个标签的高度为1,则应在刻度上添加一个:

plt.yticks([i+1 for i in range(len(trackers))],tuple(activities))

Or, more simply: 或者,更简单地说:

plt.yticks(range(1, len(trackers)+1), activities)

(As an aside, you have many inefficiencies and awkward constructions in your code. You don't need to call tuple on everything. You are probably better off iterating over things a la for item in trackers instead of for i in range(len(trackers)) .) (顺便说一句,您的代码中有许多效率低下和笨拙的构造。您无需在所有内容上调用tuple 。您可能最好for item in trackers la迭代,而不是对for i in range(len(trackers))for i in range(len(trackers))迭代for i in range(len(trackers))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM