0

I am plotting a simple dataframe in Python matplot lib using the following:

# Load the data
df = pd.read_csv('equityplot.csv')
df['Date'] = pd.to_datetime(df['Date'])  # ensure date column is datetime

# Plotting
fig, ax = plt.subplots(figsize=(10, 6))

# Iterate over each of your variables and plot
for variable in ['SP', 'RP', 'NRP', 'HRP', 'MVO', 'EW']:
    ax.plot(df['Date'], df[variable], label=variable)

# Formatting x-axis
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%b %Y'))
plt.xticks(rotation=90)

# Formatting y-axis to percentage
def to_percent(y, position):
    # Ignore the passed in position. This has the effect of scaling the default
    # tick locations.
    s = str(100 * y)

    # The percent symbol needs escaping in latex
    if plt.rcParams['text.usetex'] is True:
        return s + r'$\%$'
    else:
        return s + '%'

formatter = FuncFormatter(to_percent)
ax.yaxis.set_major_formatter(formatter)

# Add legend
ax.legend()

plt.tight_layout()
plt.show()

The resulting plot looks like the following:

enter image description here

Instead, in excel these weird breaks do not exists:

enter image description here

The dataset as simple as the following:

  • first column: dates
  • other columns: float values (the cumulative profit and loss function of trading strategies)

Can anyone explain from where this "rigidity" in the Python plot come from?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Vitomir
  • 295
  • 2
  • 14
  • This question is not reproducible without **data**. This question needs a [SSCCE](http://sscce.org/). Please see [How to provide a reproducible dataframe](https://stackoverflow.com/q/52413246/7758804), then **[edit] your question**, and paste the clipboard into a code block. Always provide a [mre] **with code, data, errors, current output, and expected output, as [formatted text](https://stackoverflow.com/help/formatting)**. If relevant, plot images are okay. If you don't include a mre, it is likely the question will be downvoted, closed, and deleted. – Trenton McKinney May 31 '23 at 17:09
  • it looks like the `pd.to_datetime(df['Date'])` does not produce the correct date. Check whether the conversion of `df['Date']` worked as expected. If not, try adding an appropriate format specifier (e.g. `pd.to_datetime(df['Date'], format='%Y-%m-%d')`) – Christian Karcher Jun 01 '23 at 06:51

0 Answers0