> For the complete documentation index, see [llms.txt](https://market-quant.gitbook.io/home/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://market-quant.gitbook.io/home/api-reference/tools/utils/barchart.md).

# BarChart()

To use BarPlotter, use the following import statement:

```python
from marketquant.tools import BarPlotter
```

The `BarPlotter` class is a utility designed to generate customizable bar charts from a pandas DataFrame. It is highly configurable, allowing you to set colors, grid options, and more. This class is intended to be modular and reusable across different applications and strategies.

***

**Constructor Arguments:**

| **Argument** | **Type**       | **Description**                                                                                                                | **Required** |
| ------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------ |
| `dataframe`  | `pd.DataFrame` | The pandas DataFrame containing the data to be plotted. It must contain columns corresponding to the x-axis and y-axis values. | Yes          |
| `x_col`      | `str`          | The column name in the DataFrame to be used for the x-axis (e.g., 'strikePrice').                                              | Yes          |
| `y_col`      | `str`          | The column name in the DataFrame to be used for the y-axis (e.g., 'gammaExposure').                                            | Yes          |

### Example Usage:

```python
import pandas as pd
from marketquant.tools.utils.bar_plotter import BarPlotter

# Example DataFrame
data = pd.DataFrame({
    'strikePrice': [200, 210, 220, 230, 240],
    'gammaExposure': [100, -50, 200, -150, 300]
})

# Initialize the BarPlotterwith the DataFrame and column names
plotter = BarPlotter(dataframe=data, x_col='strikePrice', y_col='gammaExposure')

# Plot the bar chart
plotter.plot_barchart()

```

***

## Methods in `BarPlotter`

### `validate_data()`

Validates that the provided DataFrame contains the required columns (`x_col` and `y_col`).

* **Returns**:
  * `True`: If the required columns are found.
  * `False`: If one or more required columns are missing.

#### Example:

```python
if plotter.validate_data():
    print("Data is valid.")
else:
    print("Data validation failed.")
```

***

### `plot_barchart()`

Generates and displays a bar chart with customizable options for positive and negative y-values, grid settings, and axis properties. Also allows for the inclusion of an optional line plot over the bars.

| **Argument** | **Type** | **Default Value** | **Description** |
| ------------ | -------- | ----------------- | --------------- |

| `dataframe` | `pd.DataFrame` | Required | A pandas DataFrame containing the data to be plotted. |
| ----------- | -------------- | -------- | ----------------------------------------------------- |

| `x_col` | `str` | Required | The column name for the x-axis (e.g., 'strikePrice'). |
| ------- | ----- | -------- | ----------------------------------------------------- |

| `y_col` | `str` | Required | The column name for the y-axis (e.g., 'gammaExposure'). |
| ------- | ----- | -------- | ------------------------------------------------------- |

| `figure_size` | `tuple` | `(12, 8)` | Size of the figure in inches (width, height). |
| ------------- | ------- | --------- | --------------------------------------------- |

| `dpi` | `int` | `100` | Dots per inch (DPI) for the figure resolution. |
| ----- | ----- | ----- | ---------------------------------------------- |

| `font_size` | `int` | `12` | Font size for x and y labels. |
| ----------- | ----- | ---- | ----------------------------- |

| `bar_width` | `float` | `0.8` | Width of the bars. |
| ----------- | ------- | ----- | ------------------ |

| `grid` | `bool` | `True` | Enable or disable the grid. |
| ------ | ------ | ------ | --------------------------- |

| `grid_color` | `str` | `'grey'` | Color of the grid lines. |
| ------------ | ----- | -------- | ------------------------ |

| `grid_line_style` | `str` | `'--'` | Style of the grid lines (e.g., `--`, `-`). |
| ----------------- | ----- | ------ | ------------------------------------------ |

| `grid_line_width` | `float` | `0.5` | Thickness of the grid lines. |
| ----------------- | ------- | ----- | ---------------------------- |

| `axis_color` | `str` | `'black'` | Color of the axis lines. |
| ------------ | ----- | --------- | ------------------------ |

| `tick_color` | `str` | `'black'` | Color of the tick marks. |
| ------------ | ----- | --------- | ------------------------ |

| `axis_line_width` | `float` | `1.0` | Width of the axis lines. |
| ----------------- | ------- | ----- | ------------------------ |

| `x_rotation` | `int` | `45` | Rotation angle of the x-axis labels. |
| ------------ | ----- | ---- | ------------------------------------ |

<table data-header-hidden><thead><tr><th width="187"></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><code>legend</code></td><td><code>bool</code></td><td><code>True</code></td><td>Enable or disable the legend.</td></tr></tbody></table>

| `title_font_size` | `int` | `16` | Font size of the chart title. |
| ----------------- | ----- | ---- | ----------------------------- |

| `title_font_color` | `str` | `'navy'` | Color of the chart title. |
| ------------------ | ----- | -------- | ------------------------- |

| `xlabel_font_size` | `int` | `14` | Font size for the x-axis label. |
| ------------------ | ----- | ---- | ------------------------------- |

| `ylabel_font_size` | `int` | `14` | Font size for the y-axis label. |
| ------------------ | ----- | ---- | ------------------------------- |

| `label_color` | `str` | `'purple'` | Color of both x and y-axis labels. |
| ------------- | ----- | ---------- | ---------------------------------- |

| `positive_color` | `str` | `'blue'` | Color of the bars for positive y-values (e.g., positive gamma exposure). |
| ---------------- | ----- | -------- | ------------------------------------------------------------------------ |

| `negative_color` | `str` | `'red'` | Color of the bars for negative y-values (e.g., negative gamma exposure). |
| ---------------- | ----- | ------- | ------------------------------------------------------------------------ |

| `line_data` | `dict` | `None` | Optional dictionary with keys as x-values and values as line y-values (for line overlay on the bar chart). |
| ----------- | ------ | ------ | ---------------------------------------------------------------------------------------------------------- |

| `line_color` | `str` | `'green'` | Color of the line plot data (if provided). |
| ------------ | ----- | --------- | ------------------------------------------ |

| `background_color` | `str` | `'white'` | Background color of the figure. |
| ------------------ | ----- | --------- | ------------------------------- |

**Returns:**

* Displays the bar chart using matplotlib.

**Example:**

```python
plotter.plot_barchart(
    positive_color='green',
    negative_color='orange',
    title="Custom Gamma Exposure Chart",
    background_color='lightgray',
    axis_color='navy',
    grid_color='darkgrey',
    line_data={210: 50, 220: 100, 230: -50},
    line_color='purple',
    grid=True,
    dpi=150,
    figure_size=(10, 6)
)
```

***

### `confirm_valid_data()`

Confirms that the DataFrame is valid for plotting by calling `validate_data()`.

* **Returns**:
  * `True` if the data is valid and contains the required columns.
  * `False` if the data is missing the required columns.

**Example:**

```python
if plotter.confirm_valid_data():
    print("The data is ready for plotting.")
```

***

## Full Example

```python
import pandas as pd
from marketquant.tools.utils.bar_plotter import BarPlotter

# Sample DataFrame for plotting
data = pd.DataFrame({
    'strikePrice': [210, 215, 220, 225, 230],
    'gammaExposure': [5000, -1000, 8000, -2000, 7000]
})

# Initialize the BarPlotter with all custom options
plotter = BarPlotter(
    dataframe=data,
    x_col="strikePrice",
    y_col="gammaExposure",
    figure_size=(14, 10),      # Set figure size
    dpi=120,                   # Set DPI for high resolution
    font_size=14,              # Font size for axis labels
    bar_width=0.6,             # Bar width
    grid=True,                 # Enable grid
    grid_color='lightgrey',    # Set grid color
    grid_line_style="--",      # Grid line style
    grid_line_width=0.8,       # Grid line thickness
    axis_color='darkblue',     # Color of the axis
    tick_color='darkgreen',    # Color of the tick marks
    axis_line_width=1.5,       # Width of the axis lines
    x_rotation=30,             # Rotate x-axis labels by 30 degrees
    legend=True,               # Enable legend
    title_font_size=20,        # Title font size
    title_font_color="darkred",# Title font color
    xlabel_font_size=16,       # X-axis label font size
    ylabel_font_size=16,       # Y-axis label font size
    label_color="black"        # Color of the axis labels
)

# Plot the bar chart with custom options
plotter.plot_barchart(
    positive_color='green',        # Set color for positive bars
    negative_color='orange',       # Set color for negative bars
    title="Customized Gamma Exposure Chart",  # Custom title
    background_color='white',      # Background color of the chart
    line_data={215: 1000, 225: -500},  # Add optional line plot data
    line_color='blue'              # Set line color for line plot
)
```
