Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
146 views
in Technique[技术] by (71.8m points)

python - How to align matplotlib chart in its window?

I'm trying to align the chart to the top and left side of the window, eleminating all the whitespace there. Also the labels on the x axis are cut-off for some reason, even though I'm using tight_layout(). On top of this I have trouble removing the scientific notation from the y axis. (I want to display the original str or float held in the variable, If I use plt.yaxis.set_major_formatter(ScalarFormatter(useOffset=False)) I get an attribute arror: 'matplotlib.pyplot' has no attribute 'yaxis'. This is what it looks like:

enter image description here

from binance.client import Client
import time, os, csv, datetime
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib as mpl
from matplotlib.ticker import ScalarFormatter

client = Client(apikey, apisecret)

mpl.rcParams['toolbar'] = 'None'
fig = plt.figure(figsize=(4,3))
plt.style.use('ggplot')
plt.rcParams['ytick.right'] = plt.rcParams['ytick.labelright'] = True
plt.rcParams['ytick.left'] = plt.rcParams['ytick.labelleft'] = False

x_vars = []
y_vars = []

def animate(i):
    global x_vars
    global y_vars
    if len(x_vars) > 30:
        x_vars = x_vars[-30:] 
        y_vars = y_vars[-30:] 
    else:
        pass

    current_time = client.get_server_time()
    current_price = client.get_symbol_ticker(symbol="XRPBTC")

    trstime = current_time["serverTime"] / 1000
    time = datetime.datetime.fromtimestamp(int(trstime)).strftime('%M:%S')

    x_vars.append(str(time))
    y_vars.append(float(current_price["price"]))

    plt.cla()
    plt.plot(x_vars, y_vars)
    plt.xticks(rotation = 45)  


ani = animation.FuncAnimation(fig, animate, interval=500)
plt.tight_layout()
plt.show()
question from:https://stackoverflow.com/questions/65895728/how-to-align-matplotlib-chart-in-its-window

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Set the y-axis to the right.:

ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")

Don't display offset:

plt.setp(ax.get_yaxis().get_offset_text(), visible=False)

Dealing with missing ticks (disabling tight display):

# plt.tight_layout()

To confirm this, I created an animation with the binance API and checked it. Since the essence of this question is not the animation, I think you will get faster answers from more people if you focus your question only on the graph part.

full code:

import datetime
import json
import requests
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.animation import FuncAnimation

url = "https://api.binance.com/api/v3/ticker/price?symbol=XRPBTC"

mpl.rcParams['toolbar'] = 'None'
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)

ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.setp(ax.get_yaxis().get_offset_text(), visible=False)

plt.style.use('ggplot')

x_vars = []
y_vars = []

def animate(i):
    global x_vars
    global y_vars
    if len(x_vars) > 30:
        x_vars = x_vars[-30:] 
        y_vars = y_vars[-30:] 
    else:
        pass
    current_time = 0
    current_price = 0
    r = requests.get(url) 
    response_dict = r.json()
    current_price = float(response_dict['price'])
    dt_now = datetime.datetime.now()
    ttime = '{:02}:{:02}'.format(dt_now.minute, dt_now.second)
    x_vars.append(ttime)
    y_vars.append(current_price)

    ax.cla()
    ax.plot(x_vars, y_vars)
    ax.set_xticklabels(x_vars, rotation=45)


ani = FuncAnimation(fig, animate, frames=30, interval=500, repeat=False)
# plt.tight_layout()
plt.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...