Issue
I'm using Python and I want to plot the Bitcoin price in log scale but without seeing the log price, I want to see the linear price.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from cryptocmd import CmcScraper
from math import e
from matplotlib.ticker import ScalarFormatter
# -------------IMPORT THE DATA----------------
btc_data = CmcScraper("BTC", "28-04-2012", "27-11-2022", True, True, "USD")
# Create a Dataframe
df = btc_data.get_dataframe()
#Set the index as Date instead of numerical value
df = df.set_index(pd.DatetimeIndex(df["Date"].values))
df
#Plot the Data
plt.style.use('fivethirtyeight')
plt.figure(figsize =(20, 10))
plt.title("Bitcoin Price", fontsize=18)
plt.yscale("log")
plt.plot(df["Close"])
plt.xlabel("Date", fontsize=15)
plt.ylabel("Price", fontsize=15)
plt.show()
As you can see we have log scale price but I want to see "100 - 1 000 - 10 000" instead of "10^2 - 10^3 - 10^4" on the y axis.
How do I solve this?
Solution
You were getting there, the following code will yield what you want (I simply added some fake data + 1 line of code to your plotting code):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
y = [10**x for x in np.arange(0, 5, 0.1)]
x = [x for x in np.linspace(2018, 2023, len(y))]
#Plot the Data
plt.style.use('fivethirtyeight')
plt.figure(figsize =(20, 10))
plt.title("Bitcoin Price", fontsize=18)
plt.yscale("log")
plt.plot(x, y)
plt.xlabel("Date", fontsize=15)
plt.ylabel("Price", fontsize=15)
plt.gca().get_yaxis().set_major_formatter(ticker.ScalarFormatter())
plt.show()
This generates the following figure:
The fundamental lines are these:
import matplotlib.ticker as ticker
plt.gca().get_yaxis().set_major_formatter(ticker.ScalarFormatter())
Explanation: plt.gca()
gets the currently active axis object. This object is the one we want to adapt. And the actual thing we want to adapt is the way our ticks get formatted for our y axis. Hence the latter part: .get_yaxis().set_major_formatter()
. Now, we only need to choose which formatter. I chose ScalarFormatter, which is the default for scalars. More info on your choices can be found here.
Answered By - Koedlt
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.