0

I need to set a specific tick label on a certain tick position, while deleting preexisting labels. Graph

Specifically, The labels on the x axis are dates for the value of a stock, and I want to delete those and set one for each month instead.

Date Open High Low Close/Price Volume 6/24/2019 86.78 87.11 86.06 86.55 1507828 6/25/2019 86.63 87.23 84.81 85.06 2481284 6/26/2019 85.38 85.81 84.75 85.33 2034693 6/27/2019 85.65 86.86 85.13 86.43 1394847 6/28/2019 86.66 87.74 86.66 87.55 3025379 7/1/2019 88.84 89.72 87.77 88.45 4017249 7/2/2019 89.21 90 87.95 88.87 2237183 7/3/2019 89.14 91.08 89.14 90.67 1647124


import pandas as pd
import matplotlib.pyplot as plt


def main():


    df = pd.read_excel('DatosUnited.xlsx')


    date = df['Date']
    closePrice = df['Close/Price']

    
    plt.xlabel('Tiempo')
    plt.ylabel('Valor de las acciones (USD) ')
    plt.title('Este mes')
    plt.plot(date,closePrice,'r')

    plt.show()




main()

I tried to delete all the tick labels, and set a list of new ones, but failed to set them in the desired position

1 Answers1

0

How about something like this?

import pandas as pd
import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt


df = pd.DataFrame({'Date': {0: '6/24/2019', 1: '6/25/2019', 2: '6/26/2019', 3: '6/27/2019', 4: '6/28/2019', 5: '7/1/2019', 6: '7/2/2019', 7: '7/3/2019'}, 'Open': {0: 86.78, 1: 86.63, 2: 85.38, 3: 85.65, 4: 86.66, 5: 88.84, 6: 89.21, 7: 89.14}, 'High': {0: 87.11, 1: 87.23, 2: 85.81, 3: 86.86, 4: 87.74, 5: 89.72, 6: 90.0, 7: 91.08}, 'Low': {0: 86.06, 1: 84.81, 2: 84.75, 3: 85.13, 4: 86.66, 5: 87.77, 6: 87.95, 7: 89.14}, 'Close/Price': {0: 86.55, 1: 85.06, 2: 85.33, 3: 86.43, 4: 87.55, 5: 88.45, 6: 88.87, 7: 90.67}, 'Volume': {0: 1507828, 1: 2481284, 2: 2034693, 3: 1394847, 4: 3025379, 5: 4017249, 6: 2237183, 7: 1647124}})

date = [datetime.datetime.strptime(d, '%m/%d/%Y') for d in df['Date']]
closePrice = df['Close/Price']

fig, ax = plt.subplots()
plt.xlabel('Tiempo')
plt.ylabel('Valor de las acciones (USD) ')
plt.title('Este mes')
plt.plot(date,closePrice,'r')

locator = mdates.AutoDateLocator()
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)

plt.show()

gives the following for your example data:

example line plot

You can replace AutoDateLocator() with MonthLocator() to just get months for certain, but this didn't look great for the example data. See this question for more info on matplotlib date locators.

Frodnar
  • 2,129
  • 2
  • 6
  • 20