pythonvisualizationjupyter-lablinegraph

Jupyter-lab visualisation problem (Linegraph creates non-understandable lines)


I want to create two seperate lines which shows stock prices and sentiment scores.

This my code:

import matplotlib.pyplot as plt

# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 6))

# Plot stock prices
ax.plot(tsla['Date'], tsla['Close'], color='blue', label='Stock Prices')

# Create a second y-axis
ax2 = ax.twinx()

# Plot sentiment scores
ax2.plot(tsla['Date'], tsla['sentiment_score'], color='red', label='Sentiment Scores')

# Set labels and titles
ax.set_xlabel('Date')
ax.set_ylabel('Stock Prices', color='blue')
ax2.set_ylabel('Sentiment Scores', color='red')
plt.title('Stock Prices and Sentiment Scores Over Time')

# Add legends
lines = ax.get_lines() + ax2.get_lines()
labels = [line.get_label() for line in lines]
plt.legend(lines, labels, loc='upper left')

# Rotate x-axis tick labels for better readability
plt.xticks(rotation=45)

# Show the plot
plt.show()
This my unexpected output:

enter image description here

This my sample data:

      Date Stock Name        Open       Close        High    Volume  \

12 2022-02-01 TSLA 311.736664 310.416656 314.566681 73138200
33 2022-03-01 TSLA 289.893341 288.123322 296.626678 74766900
50 2022-04-01 TSLA 360.383331 361.529999 364.916656 54263100
67 2022-06-01 TSLA 251.720001 246.789993 257.326660 77247900
86 2022-07-01 TSLA 227.000000 227.263336 230.229996 74460300

sentiment_score  

12 17.0517
33 16.8564
50 11.4832
67 12.9977
86 11.1603


Solution

  •     # I did myself like this btw
    
    import matplotlib.pyplot as plt
    
    # Extract TSLA data
    tsla_data = tsla.loc[tsla["Stock Name"] == "TSLA"]
    
    # Plotting
    fig, ax1 = plt.subplots(figsize=(10, 6))
    
    # Plotting High
    ax1.plot(tsla_data["Date"], tsla_data["High"], color='blue', label='High')
    ax1.set_xlabel('Date')
    ax1.set_ylabel('High', color='blue')
    ax1.tick_params('y', colors='blue')
    
    # Create a second y-axis for sentiment scores
    ax2 = ax1.twinx()
    ax2.plot(tsla_data["Date"], tsla_data["sentiment_score"], color='red', alpha=0.6, linestyle='--', label='Sentiment Score')
    ax2.set_ylabel('Sentiment Score', color='red')
    ax2.tick_params('y', colors='red')
    
    # Set plot title
    plt.title('TSLA High and Sentiment Score Over Time')
    
    # Add legend
    lines = ax1.get_lines() + ax2.get_lines()
    ax1.legend(lines, [line.get_label() for line in lines], loc='upper left')
    
    # Show the plot
    plt.show()

    enter image description here