My charts are changing its alignments due to the size of X-axis label names. The angle of the names also change in order to make it fit in the view. I do not want any changes in the graph alignments (which I believe is due to names printed in an angle) and also want the names in X-Axis to print normally. Graph wrong alignment images.
I have tried using the maxRotation and minRotation to 90 but here all the values are tilted to 90. I want this to be made dynamic ie. the angle must be either 0 or 90 (if the program wants to change angle).
Chartjs code
scales: {
y: {
beginAtZero : false,
ticks: {
display: false,
},
grid : {
display : false,
drawTicks : false,
drawBorder: false
},
},
x: {
maxBarThickness: 10,
ticks : {
color: 'black',
maxRotation: 90,
minRotation: 0,
autoSkip: false,
fontSize : 10,
},
grid : {
display : false,
drawTicks : false
}
}
}
HTML code to hold charts
<style>
.first {
float : left;
width: 45%;
margin: 10px;
}
</style>
<div class ="first"> <canvas id="Services"></canvas> </div>
<div class ="first"> <canvas id="VPN"> </canvas> </div>
<div class = "first"> <canvas id="Policy ID"></canvas> </div>
<div class = "first"> <canvas id="Source Country"></canvas> </div>
<div class = "first"> <canvas id="Source IP"> </canvas> </div>
<div class = "first"> <canvas id="Destination IP"></canvas> </div>
How do I achieve this where I can change the tilt angle to 90 if required ?
You can dynamically change it in the chart config itself and then call update on the chart like so:
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'pink'
},
{
label: '# of Points',
data: [7, 11, 5, 8, 3, 7],
borderColor: 'orange'
}
]
},
options: {
scales: {
x: {
ticks: {
minRotation: 0,
maxRotation: 0
}
}
}
}
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
const chart = new Chart(ctx, options);
document.getElementById("switch").addEventListener("click", () => {
chart.options.scales.x.ticks.minRotation = chart.options.scales.x.ticks.minRotation === 0 ? 90 : 0;
chart.options.scales.x.ticks.maxRotation = chart.options.scales.x.ticks.maxRotation === 0 ? 90 : 0;
chart.update();
});
<body>
<button id="switch">
Switch tick rotation
</button>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>