Codebook: From a Different Angle

Ask here about the “From a Different Angle” Codebook topic from the “Single-Qubit Gates” module.

I tried to replicate the code in my own notebook. I cannot find a source for the plotter() function. Is it from specific libraries like Plotly or matplotlib? Or is it a custom-defined function?

Hi @lawun330 , welcome to the Forum!

That’s an internal function that we had in this section of the Codebook. Here’s the code! Let me know if you have any issues with it.

def plotter(angles, amplitudes):
    """Plot the value of the output

    Args:
        angles (np.array[float]): Angles for the x axis.
        amplitudes (np.array[complex]): State after applying RX(theta)
    """

    df = pd.DataFrame(
        {
            "theta": angles,
            "|0> real": amplitudes[:, 0].real,
            "|0> imag": amplitudes[:, 0].imag,
            "|1> real": amplitudes[:, 1].real,
            "|1> imag": amplitudes[:, 1].imag,
        }
    )

    plot_1 = (
        alt.Chart(df)
        .transform_fold(["|0> real", "|1> real"], ["quantity", "amplitude"])
        .mark_line()
        .encode(x="theta:Q", y="amplitude:Q", color="quantity:N")
    )

    plot_2 = (
        alt.Chart(df)
        .transform_fold(["|0> imag", "|1> imag"], ["quantity", "amplitude"])
        .mark_line()
        .encode(x="theta:Q", y="amplitude:Q", color="quantity:N")
    )

    return plot_1 + plot_2
1 Like

I have the same problem. When I incorporate your def plotter(angles, amplitudes) into my code, I also had to import pandas as pd. But I am getting this error: “name ‘alt’ is not defined”. Is there something else I have to import?

Hi @mlowe , that’s right.
If you want to use this in your own notebook instead of the Codebook you need to import altair and pandas

import altair as alt
import pandas as pd

Thank you, the code runs when altair and pandas are imported. However no plot appears on my screen after this command: plot = plotter(angles, output_states) from Codercise 1.6.2.

Right now I am using a Jupyter notebook on a PC. Is there another command I must give in order to see a graph?

Hi @mlowe,

Just write plot as the last thing in your cell! Then you should be able to see the plot. :smiley: